BenMorel
BenMorel

Reputation: 36474

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?

Upvotes: 5

Views: 3584

Answers (3)

Kévin Dunglas
Kévin Dunglas

Reputation: 3024

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

Upvotes: 3

Matěj Koubík
Matěj Koubík

Reputation: 1147

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

Upvotes: 2

Elnur Abdurrakhimov
Elnur Abdurrakhimov

Reputation: 44831

See the @InjectParams annotation from JMSDiExtraBundle.

Upvotes: -1

Related Questions