34

私のサービスコンストラクターで

public function __construct(
        EntityManager $entityManager,
        SecurityContextInterface $securityContext)
{
     $this->securityContext = $securityContext;
    $this->entityManager = $entityManager;

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" />

でも今はコンテナをサービスで使いたい

$this->container->get('router')->generate('fos_user_profile_edit') 

コンテナーをサービスに渡すにはどうすればよいですか?

4

4 に答える 4

59

サービスが ContainerAware を拡張する場合は簡単です

use \Symfony\Component\DependencyInjection\ContainerAware;

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

service.yml

  your.service:
      class: App\...\YouService
      calls:
          - [ setContainer,[ @service_container ] ]
于 2013-06-15T18:44:31.893 に答える
49

追加:

<argument type="service" id="service_container" />

そしてリスナークラスで:

use Symfony\Component\DependencyInjection\ContainerInterface;

//...

public function __construct(ContainerInterface $container, ...) {
于 2013-06-15T17:50:51.313 に答える
14

2016年です。同じクラスを複数のライブラリで拡張するのに役立つ特性を使用できます。

<?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);
    }
}

サービスになるあなたのオブジェクト。

namespace AppBundle\Utils;

use iBasit\ToolsBundle\Utils\Lib\Container;

class myObject
{
    use Container;
}

サービス設定

 myObject: 
        class: AppBundle\Utils\myObject
        calls:
            - [setContainer, ["@service_container"]]

コントローラーでサービスを呼び出す

$myObject = $this->get('myObject');
于 2016-01-28T01:18:33.773 に答える