Container and Interface for implementing Chain of Responsibility. Allows for variable dependencies per class without hooking into a wider Service Container.
<?php
class ResolveNumberOne implements ChainableClass
{
/**
* @var int
*/
protected $number;
public function __construct($number)
{
$this->number = $number;
}
public function handle()
{
return $this->number === 1 ? 'One' : null;
}
}
class ResolveNumberTwo implements ChainableClass
{
/**
* @var int
*/
protected $number;
public function __construct($number)
{
$this->number = $number;
}
public function handle()
{
return $this->number === 2 ? 'Two' : null;
}
}
<?php
$number = 2;
// Returns "Two";
$resolved = (new ChainableClassContainer)
->chain(ResolveNumberOne::class, [ $number ])
->chain(ResolveNumberTwo::class, [ $number ])
->handle();
$number = 4;
// Returns null;
$resolved = (new ChainableClassContainer)
->chain(ResolveNumberOne::class, [ $number ])
->chain(ResolveNumberTwo::class, [ $number ])
->handle();