在symfony2 Controller中注入服务

Ars*_*ham 7 dependency-injection symfony

如何将服务(我创建的服务)注入到Controller中?二头注射就可以了.

<?php
namespace MyNamespace;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    public function setMyService(MyService $myService)
    {
        $this->myService = $myService;
    }

    public function indexAction()
    {
        //Here I cannot access $this->myService;
        //Because the setter is not called magically!
    }
}
Run Code Online (Sandbox Code Playgroud)

我的路线设置:

// Resources/routing.yml
myController_index:
    pattern:  /test
    defaults: { _controller: "FooBarBundle:MyController:index" }
Run Code Online (Sandbox Code Playgroud)

我正在另一个包中设置服务:

// Resources/services.yml 
parameters:
   my.service.class: Path\To\My\Service

services:
    my_service:
        class: %my.service.class%
Run Code Online (Sandbox Code Playgroud)

当路由解决时,不注入服务(我知道它不应该).我想在yml文件中的某个地方,我必须设置:

    calls:
        - [setMyService, [@my_service]]
Run Code Online (Sandbox Code Playgroud)

我没有将此Controller用作服务,它是一个为Request提供服务的常规Controller.

编辑:此时,我正在使用$ this-> container-> get('my_service')获取服务; 但我需要注射它.

Eln*_*mov 7

如果要将服务注入控制器,则必须将控制器定义为服务.

您还可以查看JMSDiExtraBundle 对控制器特殊处理 - 如果这样可以解决您的问题.但由于我将控制器定义为服务,我没有尝试过.


COi*_*Oil 6

使用JMSDiExtraBundle时,不必将控制器定义为服务(与@elnur不同),代码为:

<?php

namespace MyNamespace;

use JMS\DiExtraBundle\Annotation as DI;
use Path\To\My\Service;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    /**
     * @var $myService Service
     *
     * @DI\Inject("my_service")
     */
    protected $myService;

    public function indexAction()
    {
        // $this->myService->method();
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现这种方法非常好,因为你避免编写__construct()方法.