Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 Dependency Injection & autowiring

I'm browsing the Symfony 2 docs related to Dependency Injection, and can't find a reference to autowiring. I found a bundle that offers some of this functionality, but it's still in beta and seems to be tied to annotations (correct me if I'm wrong).

What I'm looking for is an object (such as the service container), that could inject dependencies in my services, via setter injection.

For example, I would define a Service:

class Service {
    /**
     * @var \PDO
     */
    protected $pdo;

    /**
     * @param \PDO $pdo
     * @Inject
     */
    public function setPDO(\PDO $pdo) {
        $this->pdo = $pdo;
    }
}

And then, I could use this hypothetical service container to inject dependencies in the Service, even if this one has been created outside the container:

$service = new Service();
// ...

$container->inject($service);

Is there a DI container that could autowire dependencies this way?

like image 686
BenMorel Avatar asked Oct 07 '22 05:10

BenMorel


2 Answers

Since Symfony 2.8, autowiring is natively supported: https://github.com/symfony/symfony/pull/15613

like image 172
Kévin Dunglas Avatar answered Oct 13 '22 10:10

Kévin Dunglas


There is also autowiring bundle aviable at https://github.com/kutny/autowiring-bundle.

like image 38
Matěj Koubík Avatar answered Oct 13 '22 11:10

Matěj Koubík