jasny / autowire
Autowiring for PSR-11 containers
Installs: 3 946
Dependents: 1
Suggesters: 0
Security: 0
Stars: 3
Watchers: 3
Forks: 1
Open Issues: 0
Requires
- php: >=7.2.0
- jasny/reflection-factory: ^1.0
- psr/container: ^1.0
Requires (Dev)
- jasny/php-code-quality: ^2.3
README
Instantiate an object (instead of using new
), automatically determining the dependencies and getting them from a
PSR-11 container.
Installation
composer require jasny/autowire
Usage
The ReflectionAutowire
implementation using reflection to determine the type of type constructor parameters.
class Foo { public function __construct(ColorInterface $color) { // ... } }
Create a new Foo
object with autowiring:
use Jasny\Autowire\ReflectionAutowire(); $autowire = new ReflectionAutowire($container); $foo = $autowire->instantiate(Foo::class); // OR $foo = $autowire(Foo::class);
Optional parameters
If the argument may be null
, it will be set to null
if no container entry for the parameter exists.
class Foo { public function __construct(?ColorInterface $color) { // ... } }
Doc comments
It also parses the doc comment and can get entry name
from @param
. Entry names must be the first part of the description and surrounded by double quotes.
class Bar { /** * Class constructor * * @param string $color "config:bar_color" * @param ConnectionInterface $connection "db_connections.default" */ public function __construct(string $color, ConnectionInterface $connection) { // ... } }
The type from @param
is not considered. If the type is a single interface (or class), there is little reason not to
use type hints in the method parameters. Parsing them is difficult, because it requires converting a class to a
fully-qualified-class-name (FQCN), which requires looking at the namespace and use
statements.
This library deliberately doesn't support autowiring for properties or methods. Please explicitly call those methods in the container function or use an abstract factory.
Non-wired parameters
Additional arguments in instantiate()
are passed directly to the constructor. No autowiring is applied to these
parameters.
class Bar { /** * Class constructor * * @param string $color A color * @param ConnectionInterface $connection "db_connections.default" */ public function __construct(string $color, ConnectionInterface $connection) { // ... } }
use Jasny\Autowire\ReflectionAutowire(); $autowire = new ReflectionAutowire($container); $foo = $autowire->instantiate(Foo::class, 'blue');
The constructor MUST begin with these parameters. It's not possible to cherry-pick the parameters than need to be autowired.