访问控制器外部的容器但不能注入服务

时间:2016-11-30 20:49:37

标签: php symfony

由于我使用某些类的方式,我无法进行服务注入,但我需要访问其中的服务容器。

namespace DocumentsUploadSystem;

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

class DocumentsUpload implements ContainerAwareInterface
{
    use ContainerAwareTrait;

        public function getData()
    {
        var_dump($this->container);
    }

}

如果我从控制器那样调用这个方法。

use DocumentsUploadSystem\DocumentsUpload
...

$x = new DocumentsUpload($request)->getData();

我没有错误,但容器返回null。这是实现ContainerAwareInterface的错误方法吗?我正在使用Symfony 3.1

2 个答案:

答案 0 :(得分:0)

实现接口不会做任何事情。接口是类的构建器和类的用户之间的契约,保证某些方法的存在 - 这就是全部。在这种情况下,ContainerAwareInterface保证setContainer()方法可用。然后,您必须 USE 才能设置容器。

// MyController extends Symfony\Bundle\FrameworkBundle\Controller\Controller
use DocumentsUploadSystem\DocumentsUpload
...

$x = new DocumentsUpload($request);
$x->setContainer($this->container);
$xData = $x->getData();

为了记录,我不建议注入整个容器 - 只需要完成任务所需的实际服务。

KnpMenuBundle这样的库似乎正在使用它,但实际上,它们会自动创建菜单并为您注入容器。见https://github.com/KnpLabs/KnpMenuBundle/blob/master/Provider/BuilderAliasProvider.php#L122-L124

祝你好运!

答案 1 :(得分:0)

但是在这个例子中[https://symfony.com/doc/current/bundles/KnpMenuBundle/index.html]他们使用相同的技术并且访问容器很好,它在那里工作,是否为其他服务调用呢?

// src/AppBundle/Menu/Builder.php
namespace AppBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;

class Builder implements ContainerAwareInterface
{
    use ContainerAwareTrait;

    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $em = $this->container->get('doctrine')->getManager();
    }
}