如何将容器作为服务的参数

whi*_*ear 29 php symfony symfony-2.3

在我的服务构造函数中

public function __construct(
        EntityManager $entityManager,
        SecurityContextInterface $securityContext)
{
     $this->securityContext = $securityContext;
    $this->entityManager = $entityManager;
Run Code Online (Sandbox Code Playgroud)

我将entityManager和securityContext作为参数传递.我的services.xml也在这里

    <service id="acme.memberbundle.calendar_listener" class="Acme\MemberBundle\EventListener\CalendarEventListener">
        <argument type="service" id="doctrine.orm.entity_manager" />
        <argument type="service" id="security.context" />
Run Code Online (Sandbox Code Playgroud)

但现在,我想在服务中使用容器

$this->container->get('router')->generate('fos_user_profile_edit') 
Run Code Online (Sandbox Code Playgroud)

我怎样才能将容器传递给服务?

big*_*max 57

如果服务扩展了ContainerAware,那很容易

use \Symfony\Component\DependencyInjection\ContainerAware;

class YouService extends ContainerAware
{
    public function someMethod() 
    {
        $this->container->get('router')->generate('fos_user_profile_edit') 
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

service.yml

  your.service:
      class: App\...\YouService
      calls:
          - [ setContainer,[ @service_container ] ]
Run Code Online (Sandbox Code Playgroud)

  • 我必须添加:`protected $container; 公共函数 __construct($container) { $this-&gt;container = $container; }` 而不是 `calls: - [ setContainer,[ @service_container ] ]` 我在 services.yml 中使用了 `arguments: [ '@service_container' ]` 来让它在 Symfony 2.8 中工作。除此之外一切都工作正常。谢谢。 (2认同)

Syb*_*bio 47

加:

<argument type="service" id="service_container" />
Run Code Online (Sandbox Code Playgroud)

在你的听众课上:

use Symfony\Component\DependencyInjection\ContainerInterface;

//...

public function __construct(ContainerInterface $container, ...) {
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,你应该使用__construct(ContainerInterface $ container,..),因为你可能没有使用容器界面中没有定义的任何函数. (2认同)

Bas*_*sit 14

这是2016年,您可以使用trait来帮助您使用多个库扩展同一个类.

<?php

namespace iBasit\ToolsBundle\Utils\Lib;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Symfony\Component\DependencyInjection\ContainerInterface;

trait Container
{
    private $container;

    public function setContainer (ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Shortcut to return the Doctrine Registry service.
     *
     * @return Registry
     *
     * @throws \LogicException If DoctrineBundle is not available
     */
    protected function getDoctrine()
    {
        if (!$this->container->has('doctrine')) {
            throw new \LogicException('The DoctrineBundle is not registered in your application.');
        }

        return $this->container->get('doctrine');
    }

    /**
     * Get a user from the Security Token Storage.
     *
     * @return mixed
     *
     * @throws \LogicException If SecurityBundle is not available
     *
     * @see TokenInterface::getUser()
     */
    protected function getUser()
    {
        if (!$this->container->has('security.token_storage')) {
            throw new \LogicException('The SecurityBundle is not registered in your application.');
        }

        if (null === $token = $this->container->get('security.token_storage')->getToken()) {
            return;
        }

        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }

        return $user;
    }

    /**
     * Returns true if the service id is defined.
     *
     * @param string $id The service id
     *
     * @return bool true if the service id is defined, false otherwise
     */
    protected function has ($id)
    {
        return $this->container->has($id);
    }

    /**
     * Gets a container service by its id.
     *
     * @param string $id The service id
     *
     * @return object The service
     */
    protected function get ($id)
    {
        if ('request' === $id)
        {
            @trigger_error('The "request" service is deprecated and will be removed in 3.0. Add a typehint for Symfony\\Component\\HttpFoundation\\Request to your controller parameters to retrieve the request instead.', E_USER_DEPRECATED);
        }

        return $this->container->get($id);
    }

    /**
     * Gets a container configuration parameter by its name.
     *
     * @param string $name The parameter name
     *
     * @return mixed
     */
    protected function getParameter ($name)
    {
        return $this->container->getParameter($name);
    }
}
Run Code Online (Sandbox Code Playgroud)

你的对象,这将是服务.

namespace AppBundle\Utils;

use iBasit\ToolsBundle\Utils\Lib\Container;

class myObject
{
    use Container;
}
Run Code Online (Sandbox Code Playgroud)

您的服务设置

 myObject: 
        class: AppBundle\Utils\myObject
        calls:
            - [setContainer, ["@service_container"]]
Run Code Online (Sandbox Code Playgroud)

在控制器中调用您的服务

$myObject = $this->get('myObject');
Run Code Online (Sandbox Code Playgroud)

  • 与smf3只是"使用\ Symfony\Component\DependencyInjection\ContainerAwareTrait;" (5认同)

Ala*_*blo 5

如果您的所有服务都是ContainerAware,我建议创建一个BaseService类,其中包含与您的其他服务相关的所有公共代码.

1)创建Base\BaseService.php课程:

<?php

namespace Fuz\GenyBundle\Base;

use Symfony\Component\DependencyInjection\ContainerAware;

abstract class BaseService extends ContainerAware
{

}
Run Code Online (Sandbox Code Playgroud)

2)将此服务注册为您的摘要 services.yml

parameters:
    // ...
    geny.base.class: Fuz\GenyBundle\Base\BaseService

services:
    // ...
    geny.base:
        class: %geny.base.class%
        abstract: true
        calls:
          - [setContainer, [@service_container]]
Run Code Online (Sandbox Code Playgroud)

3)现在,在您的其他服务中,扩展您的BaseService课程而不是 ContainerAware:

<?php

namespace Fuz\GenyBundle\Services;

use Fuz\GenyBundle\Base\BaseService;

class Loader extends BaseService
{
   // ...
}
Run Code Online (Sandbox Code Playgroud)

4)最后,您可以parent在服务声明中使用该选项.

geny.loader:
    class: %geny.loader.class%
    parent: geny.base
Run Code Online (Sandbox Code Playgroud)

我更喜欢这种方式有几个原因:

  • 代码和配置之间存在一致性
  • 这避免了为每个服务重复过多的配置
  • 每个服务都有一个基类,对常用代码非常有帮助