Last active
April 18, 2017 13:58
-
-
Save weaverryan/fdc77d2190755ce9fd51637eb6423196 to your computer and use it in GitHub Desktop.
Autowiring controller args
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 thesecurity.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 withsecurity.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. theLoggerInterface
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.