Capsule DI and Argument Inheritance
source link: http://paul-m-jones.com/post/2022/01/01/capsule-di-and-argument-inheritance/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Capsule DI and Argument Inheritance
I am pleased to announce that I have released Capsule version 3.4.0, now with argument inheritance. (You can see the rest of the changes here.)
As an autowiring dependency injection system for PHP 8.0+, Capsule supports injection of constructor arguments. With the 3.4.0 release, each class defined in Capsule now "inherits" the constructor arguments of its parent. This means you can specify a constructor argument on a parent class, and the child class will use it (that is, unless you set an overriding value on the child class).
Let's say you have this class hierarchy:
abstract class Strategy
{
public function __construct(
protected string $path
) {
}
abstract public function doSomething() : string;
}
class FooStrategy extends Strategy
{
public function doSomething() : string
{
// ...
}
}
class BarStrategy extends Strategy
{
public function doSomething() : string
{
// ...
}
}
If you define the constructor arguments for the parent ...
$def->{Strategy::CLASS}
->argument('path', '/path/to/resources');
... both FooStrategy
and BarStrategy
will automatically "inherit" the
defined $path
value. You won't have to re-define it for every Strategy
class extension.
You can always override the "inherited" values by specifying them for the child class directly ...
$def->{FooStrategy::CLASS}
->argument('path', '/path/to/other-resoruces');
... in which case the children of that class will inherit the override value. In this way, constructor arguments can be propagated down the inheritance hierarchy.
If you decide that want to disable or interrupt the "inheritance" of arguments for a class, call inherit(null)
on its definition:
$def->{BarStrategy::CLASS}
->inherit(null);
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK