Create chains with reusable steps for better domain logic structure
composer require aambr/phpchain
Start with definition of a chain, each step can be instance of ChainStep or string, which is resolved using injected dependency injection container.
$dispatcher = new ChainDispatcher($dependencyInjectionContainer);
$dispatcher->define('user.register', [
'Domain\Steps\CreateUserStep',
Domain\Steps\CreateProfileStep::class,
'sendWelcomeEmail'
]); // all of these will be resolved by dependency container unless
// there is a concrete ChainStep object ready
$dispatcher->dispatch('user.register')->execute(new \ArrayObject([
'username' => 'valid-username',
'email' => 'valid@email.com'
])); // steps can modify \ArrayObject (passed by reference)ChainDispatcher accepts any dependency injection container which comply with Container Interoperability interface.
The goal is to devide complex domain logic into individual steps that can be reused in future processes.
Create your own steps by inheriting ChainStep and implement logic in process(\ArrayObject $input).
Steps can share variables between each other by altering $input keys, which is possible because we
are passing \ArrayObject instance reference instead an array which is passed by value. For example
CreateUserStep after successful action can set $input['user'] = $createdUser, which then can be used
by sendWelcomeEmail.