schorts / shared-kernel
Shared kernel value objects and domain abstractions
v3.0.1
2026-11-06 15:01 UTC
Requires
None
Requires (Dev)
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Shared kernel value objects and domain abstractions for building domain-driven PHP applications.
A modular, type-safe foundation for building expressive, maintainable applications. This package provides core abstractions for domain modeling, CQRS, event-driven architectures, access control, state management, and persistence โ framework-agnostic and extensible.
๐ฆ Installation
Require the package via Composer:
composer require schorts/shared-kernel
Composer will autoload classes under the namespace:
Schorts\SharedKernel\
For example:
use Schorts\SharedKernel\ValueObjects\EmailValue; use Schorts\SharedKernel\CQRS\CommandBus\InMemoryCommandBus; use Schorts\SharedKernel\EventBus\InMemoryEventBus;
๐งฉ Architecture & Features
๐งฌ Core Domain & DDD
- Value Objects: Immutable primitives with validation and equality logic:
StringValue,IntegerValue,FloatValue,BooleanValue,DateValueEmailValue,URLValue,PhoneValue,SlugValue,UUIDValueHtmlValue,MarkdownValue,PathValueArrayValue,ObjectValue,EnumValue,CoordinatesValueValueNotValid&ValuesNotValiddomain exceptions.- Implements
\JsonSerializableand\Stringable.
- Entities:
Entity: Identity-based entity with domain event recording andpullDomainEvents.EntityRegistry: Registry for hydrating entities polymorphically from primitives or factories.
- Aggregate Roots:
AggregateRoot: ExtendsEntitywith versioning, uncommitted-change tracking, domain-event sequencing, snapshots, andfromPrimitives/fromSnapshotfactory methods.
- Result Type:
Result: Encapsulate success and failure outcomes without throwing. IncludesfromCallable,map,flatMap,mapError,combine,toPrimitives, andfromPrimitives.
โ๏ธ Command & Query Processing (CQRS)
- Commands:
Commandinterface andAbstractCommandbase class with metadata, causation/correlation IDs, headers, and context.CommandRegistryfor polymorphic hydration from primitives.- Built-in error types:
CommandNotRegistered,CommandAlreadyRegistered,CommandHandlerNotRegistered.
- Command Handlers:
CommandHandlerinterface with pipeline:validateโauthorizeโexecute.AbstractCommandHandlerwith automatic retries, idempotency support, logging, and metrics.- Built-in error types:
CommandValidationError,CommandAuthorizationError,CommandExecutionError,CommandMaxRetriesExceeded.
- Command Bus:
CommandBusinterface andInMemoryCommandBusdispatcher.- Full middleware pipeline (
beforeDispatch,afterDispatch,onError). - Unit of Work transactional integration and auto-event publishing.
- Queries & Query Bus:
Queryinterface andAbstractQuerybase class.QueryHandlerandAbstractQueryHandlerwith caching, logging, and metrics.InMemoryQueryBuswith middleware and bulk dispatch (dispatchMany).
๐ก Event Bus & Messaging
- Domain Events:
DomainEventbase class with metadata, correlation/causation tracking, and primitives serialization.DomainEventRegistryfor hydrating events from serialized payloads.
- Event Bus:
EventBuscontract andInMemoryEventBusimplementation.- Priority-based subscriber ordering.
- Automatic retries on subscriber failure.
DeadLetterStoreandInMemoryDeadLetterStorefor capturing failed deliveries.EventStoreandInMemoryEventStorefor auditing and event replays.EventSubscriberandAbstractEventSubscriber.
๐ก๏ธ Access Control (RBAC & ABAC)
- RBAC (Role-Based Access Control):
Permission: Resource-action mapping (e.g.'document','write') supporting wildcards ('*') and manage actions.RBACPolicy: Base class for defining role-based permissions and evaluatingcan($roles, $action, $resource).
- ABAC (Attribute-Based Access Control):
Predicate: Composable attribute predicates to evaluate dynamic context (e.g. ownership, tenant limits).- Evaluated via
canWithAttributesandcanAnyWithAttributes.
๐พ Persistence & Unit of Work
- DAO (Data Access Object):
DAOinterface defining CRUD operations with Criteria filtering and soft/hard delete modes.InMemoryDAO: Full in-memory implementation supporting Criteria filtering, sorting, pagination, and soft deletion.
- Unit of Work:
UnitOfWorkandInMemoryUnitOfWorkfor transactional coordination with commit/rollback hooks.TransactionalUnitOfWorkRunnerfor automatic transaction management.
- Criteria:
- Fluent query builder with methods:
whereEqual,whereNotEqual,whereIn,whereNotIn,whereGreaterThan,whereLessThan,whereLike,whereBetween,orderBy,limitResults, andoffsetResults.
- Fluent query builder with methods:
๐ป Infrastructure & Utilities
- Cache:
Cacheinterface andInMemoryCachewith TTL and tag-based invalidation. - Idempotency:
IdempotencyStoreandInMemoryIdempotencyStore. - Logger:
Logger,ConsoleLogger,InMemoryLogger,NullLogger,CompositeLogger, andScopedLogger. - i18n:
TranslationResolvercontract for localized domain messages.
๐ Usage Examples
1. Value Objects
use Schorts\SharedKernel\ValueObjects\EmailValue; use Schorts\SharedKernel\ValueObjects\Exceptions\ValueNotValid; class UserEmail extends EmailValue { public function getAttributeName(): string { return 'user_email'; } } $email = new UserEmail('user@example.com'); if (!$email->isValid()) { throw new ValueNotValid($email->getAttributeName()); } echo (string) $email; // user@example.com
2. CQRS Commands & Command Bus
use Schorts\SharedKernel\CQRS\Command\AbstractCommand; use Schorts\SharedKernel\CQRS\CommandHandler\AbstractCommandHandler; use Schorts\SharedKernel\CQRS\CommandHandler\CommandHandlerContext; use Schorts\SharedKernel\CQRS\CommandBus\InMemoryCommandBus; final class RegisterUserCommand extends AbstractCommand { public function getType(): string { return 'user.register'; } } final class RegisterUserHandler extends AbstractCommandHandler { protected function execute(Command $command, CommandHandlerContext $context): mixed { $payload = $command->getPayload(); // Execute domain logic ... return ['userId' => 'usr_123']; } } $bus = new InMemoryCommandBus(); $bus->register('user.register', new RegisterUserHandler()); $command = new RegisterUserCommand('correlation-id-1', ['email' => 'alice@example.com']); $result = $bus->dispatch($command);
3. Domain Events & Event Bus
use Schorts\SharedKernel\DomainEvent\DomainEvent; use Schorts\SharedKernel\EventBus\AbstractEventSubscriber; use Schorts\SharedKernel\EventBus\InMemoryEventBus; final class UserRegisteredEvent extends DomainEvent { public function getEventName(): string { return 'user.registered'; } } final class SendWelcomeEmailSubscriber extends AbstractEventSubscriber { public function subscribedTo(): array { return ['user.registered']; } public function handle(DomainEvent $event, ?EventSubscriberContext $context = null): void { $email = $event->getPayload()['email']; // Send email ... } } $eventBus = new InMemoryEventBus(); $eventBus->registerSubscriber(new SendWelcomeEmailSubscriber()); $eventBus->publish(new UserRegisteredEvent('corr-1', ['email' => 'alice@example.com']));
4. Result Pattern
use Schorts\SharedKernel\Result\Result; function divide(float $a, float $b): Result { if ($b === 0.0) { return Result::failure('Cannot divide by zero'); } return Result::success($a / $b); } $result = divide(10.0, 2.0) ->map(fn (float $val) => $val * 10); if ($result->isSuccess()) { echo $result->getValue(); // 50 }
5. Access Control (RBAC & ABAC)
use Schorts\SharedKernel\RBAC\Permission; use Schorts\SharedKernel\RBAC\RBACPolicy; use Schorts\SharedKernel\RBAC\BaseResource; class DocumentPolicy extends RBACPolicy { public function getPermissions(string $role): array { return match ($role) { 'admin' => [new Permission('*', '*')], 'editor' => [new Permission('document', 'write'), new Permission('document', 'read')], 'viewer' => [new Permission('document', 'read')], default => [], }; } } $policy = new DocumentPolicy(); $canWrite = $policy->can('editor', 'write', 'document'); // true
๐งช Testing
Run the test suite via PHPUnit:
composer test # or php vendor/bin/phpunit
๐ License
LGPL-3.0-or-later