创建实现ContainerAwareInterface的服务

时间:2013-07-05 08:53:22

标签: symfony

当我扩展ContainerAware或实现ContainerAwareInterface时,服务不会调用setContainer。

class CustomService implements ContainerAwareInterface
{
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }
}

如何在没有注射的情况下使用我服务中的容器? 是否需要将容器对象传递给构造函数或setter?

5 个答案:

答案 0 :(得分:7)

在services.yml文件中定义

services:
    bundle.service_name: 
        class: ...
        calls:
            - [ setContainer, [ @service_container ] ]

答案 1 :(得分:5)

您必须将服务名称放在引号内:

services:
    bundle.service_name: 
        class: ...
        calls:
            - [ setContainer, [ '@service_container' ]]

答案 2 :(得分:3)

仅实施ContainerAwareContainerAwareInterface是不够的。您必须使用service_container作为参数调用setter注入。 但不建议注入完整的容器。最好只注入您真正需要的服务。

答案 3 :(得分:2)

这是一个完整实现容器感知服务的示例。

但请注意,应避免注入整个容器。最佳做法是仅注入所需的组件。有关该主题的更多信息,请参阅Law of Demeter - Wikipedia

为此,此命令将帮助您找到所有可用的服务:

# symfony < 3.0
php app/console debug:container

# symfony >= 3.0
php bin/console debug:container

无论如何,这是完整的例子。

app/config/services.yml文件:

app.my_service:
    class: AppBundle\Service\MyService
    calls:
        - [setContainer, ['@service_container']]

src/AppBundle/Service/MyService.php中的服务类:

<?php

namespace AppBundle\Service;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class MyService implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function useTheContainer()
    {
        // do something with the container
        $container = $this->container;
    }
}

最后你的控制器在src/AppBundle/Controller/MyController.php

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

/**
 * My controller.
 */
class MyController extends Controller
{
    /**
     * @Route("/", name="app_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $myService = $this->get('app.my_service');
        $myService->useTheContainer();

        return new Response();
    }
}

答案 4 :(得分:1)

您还可以使用ContainerAwareTrait来实现ContainerAwareInterface。