jasny/autowire

This package is abandoned and no longer maintained. No replacement package was suggested.

Autowiring for PSR-11 containers

v1.2.2 2020-04-19 06:11 UTC

This package is auto-updated.

Last update: 2023-05-29 23:47:21 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Packagist Stable Version Packagist License

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.