Forget "autowire" and just use it

Found a typo? Edit me
This post is deprecated since May 2017. Its knowledge is old and should not be used.
Why?

You can set autowiring via new _defaults per config file feature since Symfony 3.3.

It does pretty much the same thing, with advantage of having it under control and explicitly defined.

I recommend using it instead!


Autowiring is a great feature that was added in Symfony 2.8. It moves Dependency Injection pattern to the next level. If you want to use it to its full potential, you still have to add 1 extra line to every service configuration. Today I will show you, how to get rid of that line.

When to autowire?

If you use autowiring daily, you might came across this thinking process before you place autowired: true to your config:

1) Has this service constructor dependency?

2) Is it object?

3) Is it unique service type?

4) Has the constructor changed during development?

Plus some more logic for edge cases like parameters and factories.

Seems like function... Could this be automated?

You are right! It can be automated.

This is exactly what Symplify/DefaultAutowire bundle does.

Apart handling feature above for you, it will turn this...

# app/config/config.yml
services:
    PriceCalculator:
        autowire: true

    ProductRepository:
        autowire: true

    UserFactory:
        autowire: true

...into this:

# app/config/config.yml
services:
    PriceCalculator: ~

    ProductRepository: ~

    UserFactory: ~

Get It Done in 2 steps

1. Install package

composer require symplify/default-autowire

2. Register bundle

// app/AppKernel.php

final class AppKernel extends Kernel
{
    public function registerBundles(): array
    {
        $bundles = [
            new Symplify\DefaultAutowire\SymplifyDefaultAutowireBundle(),
            // ...
        ];
    }
}

And that's it!

For further use, just check Readme for Symplify/DefaultAutowire.


Have you find this post useful? Do you want more?

Follow me on Twitter, RSS or support me on GitHub Sponsors.