Instantiate an object (instead of using new
), automatically determining the dependencies and getting them from a
PSR-11 container.
composer require jasny/autowire
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);
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)
{
// ...
}
}
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.
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.