leads/core
Composer 安装命令:
composer require leads/core
包简介
Shared core library for Leads
README 文档
README
Shared core bundle for Leads projects built on the Symfony Framework. It provides a lightweight command bus, DBAL-based pagination, API request validation helpers and base controller utilities.
Requirements
- PHP >= 8.3
- Symfony 7.2+ or 8.x (the package resolves to Symfony 8.x on PHP >= 8.4)
- Doctrine DBAL ^4.0 (used by the pagination component)
Installation
composer require leads/core
Register the bundle in config/bundles.php (done automatically if you use Symfony Flex):
return [ // ... Leads\Core\LeadsCoreBundle::class => ['all' => true], ];
Command bus
A minimal synchronous command bus. Handlers and validators are discovered by PHP attributes and wired at container compile time; they are instantiated lazily through a service locator — only when their command is actually dispatched.
1. Define a command
use Leads\Core\CommandBus\CommandInterface; final readonly class CreateOrderCommand implements CommandInterface { public function __construct( public string $customerId, public int $amount, ) { } }
2. Define a handler
Exactly one handler per command, marked with #[AsCommandHandler]:
use Leads\Core\CommandBus\AsCommandHandler; use Leads\Core\CommandBus\CommandInterface; use Leads\Core\CommandBus\HandlerInterface; /** * @implements HandlerInterface<CreateOrderCommand> */ #[AsCommandHandler(commandClass: CreateOrderCommand::class)] final readonly class CreateOrderHandler implements HandlerInterface { /** * @param CreateOrderCommand $command */ public function handle(CommandInterface $command) { // create the order, return whatever the caller needs (e.g. an id) } }
3. Define validators (optional)
Any number of validators per command, marked with #[AsCommandValidator]. All matching validators run before the handler; a validator reports failure by throwing CommandValidatorException:
use Leads\Core\CommandBus\AsCommandValidator; use Leads\Core\CommandBus\CommandInterface; use Leads\Core\CommandBus\CommandValidatorException; use Leads\Core\CommandBus\CommandValidatorInterface; /** * @implements CommandValidatorInterface<CreateOrderCommand> */ #[AsCommandValidator(commandClass: CreateOrderCommand::class)] final readonly class CreateOrderAmountValidator implements CommandValidatorInterface { /** * @param CreateOrderCommand $command */ public function validate(CommandInterface $command): void { if ($command->amount <= 0) { throw new CommandValidatorException('Amount must be positive.'); } } }
4. Dispatch
Inject CommandBus and call handle():
use Leads\Core\CommandBus\CommandBus; final readonly class OrderService { public function __construct( private CommandBus $commandBus, ) { } public function createOrder(string $customerId, int $amount): mixed { return $this->commandBus->handle(new CreateOrderCommand($customerId, $amount)); } }
Exceptions thrown by CommandBus::handle():
Leads\Core\CommandBus\CommandValidatorException— a validator rejected the command (default code 400)Leads\Core\CommandBus\HandlerNotFoundException— no handler is registered for the command class
Pagination
Page-based pagination over a Doctrine DBAL QueryBuilder. The Leads\Core\Pagination namespace is excluded from container autowiring — instantiate the classes manually:
use Doctrine\DBAL\Connection; use Leads\Core\Pagination\DBALPagination; use Leads\Core\Pagination\DTO\ListResponseDTO; use Leads\Core\Pagination\Pagination; final readonly class OrderRepository { public function __construct( private Connection $connection, ) { } public function findPaginated(int $page, int $perPage): ListResponseDTO { $qb = $this->connection->createQueryBuilder() ->select('id', 'customer_id', 'amount') ->from('orders') ->orderBy('id', 'DESC'); return (new Pagination( page: $page, perPage: $perPage, pagination: new DBALPagination( connection: $this->connection, qb: $qb, ), ))->paginate(); } }
paginate() returns a ListResponseDTO:
items— the rows for the requested page (fetchAllAssociative()result)pagination— aPaginationDTOwithcount(items on this page),total(total rows),page,perPageandpages(total page count)
The total is computed by wrapping your query in a COUNT(*) subquery (with ORDER BY stripped), so it stays correct for queries with GROUP BY or DISTINCT. Pagination throws \InvalidArgumentException if page or perPage is less than 1.
To paginate a different data source, implement Leads\Core\Pagination\PaginationInterface (getItems(int $offset, int $limit): array and getTotal(): int) and pass it instead of DBALPagination.
API validation and base controller
ApiValidator wraps the Symfony Validator: it validates an object against its constraint attributes and throws ApiValidationException if there are violations. The exception exposes the violations as getErrors() — a list of ['property' => ..., 'message' => ...] pairs, also JSON-encoded into the exception message.
Controllers can extend BaseAction to get validation plus JSON response helpers:
use Leads\Core\Action\BaseAction; use Symfony\Component\HttpFoundation\JsonResponse; final class CreateOrderAction extends BaseAction { public function __invoke(CreateOrderRequest $request): JsonResponse { $this->validate($request); // throws ApiValidationException on violations $id = /* ... */; return $this->create201Response($id); // {"id": "..."} } }
Available response helpers:
create200Response(array $data)— 200 with a JSON bodycreate201Response(string $id)— 201 with{"id": ...}create201ContentResponse(array $response)— 201 with a custom bodycreate201EmptyResponse()— 201 with an empty bodycreate204Response()— 204create400Response(string $message)— 400 with a messagecreateCustomResponse(array $data, int $status)— any status
ApiValidatorInterface is autowired to ApiValidator by the bundle; you can also inject it directly into your own services.
Exceptions
Leads\Core\Exception\EntityNotFoundException— a\LogicExceptionwith messageEntity not foundand code 404, for signalling missing entities from repositories/handlers.
License
MIT
leads/core 适用场景与选型建议
leads/core 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 16.14k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 leads/core 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 leads/core 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 16.14k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 1
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-19