Skip to content
This repository has been archived by the owner on May 29, 2023. It is now read-only.
/ autowire Public archive

Autowiring for PSR-11 containers

License

Notifications You must be signed in to change notification settings

jasny/autowire

Repository files navigation

Autowire for PSR-11 containers

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.