AlvaroCasvi
AlvaroCasvi

Reputation: 125

Symfony 2 dependency injection into the Controller construct

I've tried to add many services into the construct of a Controller without success.

class PersonController extends Controller
{
    public function __construct(UtilityService $Utils)
    {
        $this->util = $Utils;
    }

    public function indexAction()
    {
        ...
    }

}

what's the path I must follow?

Upvotes: 4

Views: 457

Answers (2)

Victor Bocharsky
Victor Bocharsky

Reputation: 12306

You need to define your PersonController controller as a service in services.yml and inject to them UtilityService:

# src/Acme/HelloBundle/Resources/config/services.yml
parameters:
    # ...
    person.controller.class: Acme\HelloBundle\Controller\PersonController

services:
    person.controller:
        class: "%person.controller.class%"
        arguments: ["@UtilityService"]

Where:

  1. person.controller.class is a name of your controller class
  2. UtilityService in arguments is a name of servicem which you want to inject

Upvotes: 2

Lt.
Lt.

Reputation: 1268

as @Cerad mention in this post:

The trick is to define your controllers as services and then use the service id instead of the class name.

http://symfony.com/doc/current/cookbook/controller/service.html

Upvotes: 1

Related Questions