Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Last active April 18, 2017 13:58
Show Gist options
  • Save weaverryan/fdc77d2190755ce9fd51637eb6423196 to your computer and use it in GitHub Desktop.
Save weaverryan/fdc77d2190755ce9fd51637eb6423196 to your computer and use it in GitHub Desktop.
Autowiring controller args
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Psr\Log\LoggerInterface;
/**
* This class is now a service, so you can use normal __construct DI if you want!
*/
class FooController extends Controller
{
/**
* @Route("/cool")
*
* In the controller, type-hint an arg and Symfony will pass you the matching service
*/
public function doCoolStuffAction(LoggerInterface $logger)
{
$logger->info('Huh, that was easy');
// even though your controller is now a service, you can still use
// $this->container->get('some_other_service');
// if you want to, just like before
}
}
services:
_defaults:
autowire: true
# auto-tags services based on their class whenever it makes sense
autoconfigure: true
# registers all classes found in these directories
AppBundle\:
resource: '../../src/AppBundle/{Controller,Service,OtherDir}'
@Pierstoval
Copy link

What is this autoconfigure: true? I know about autowiring and resources, but it seems it brings a lot of uncontrollable magic 😕

@weaverryan
Copy link
Author

@Pierstoval Great question :). This actually hasn't gotten merged yet - but it most likely will: symfony/symfony#22234. It does one simple thing: it automatically adds tags based on interfaces (for services defined in this file). For example, if you create a service for a class that implements VoterInterface, you no longer need to manually add the security.voter tag - Symfony does it for you. I think it will cause very little or no issues. After all, when would you ever register a service whose class implements VoterInterface, but NOT want your service to be tagged with security.voter :).

In this case, it auto-tags your controllers (because they extends AbstractController) with a tag that makes it possible to have services passed to your action methods (e.g. the LoggerInterface arg). Needing to worry about that tag sucks, so we do it for you. And if you don't want to use this feature, it doesn't hurt anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment