【发布时间】:2017-01-02 03:07:30
【问题描述】:
我注意到一些奇怪的行为,甚至可能是 symfony 中的错误?我不知道...这里是reprocuce的步骤:
1。安装 symfony
>我全新安装了 symfony 3.1.3,使用 cli 安装程序安装:
$ symfony new myproject
2。添加一些服务
我在app/config/services.yml中添加了一个服务定义:
services:
app.helper:
class: AppBundle\Service\AppHelper
arguments: ["@service_container"]
并且我添加了相应的服务类:
<?php
namespace AppBundle\Service;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AppHelper
{
/**
* @var ContainerInterface
*/
private $container;
/**
* @var \Doctrine\ORM\EntityManager
*/
private $em;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->em = $this->container->get('doctrine.orm.entity_manager');
}
/**
* Returns stuff.
*
* @param $key
* @return mixed
*/
public function getStuff($key)
{
return $this->em->... // get stuff
}
}
在构造函数中,我注入容器并从中获取理论实体管理器。到目前为止工作正常,例如在控制器内部。
3。添加编译器通道
然后我添加了一个带有空进程方法的编译器类:
<?php
namespace AppBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class MenuItemCompilerPass implements CompilerPassInterface
{
/**
* Collect modules menu items.
*
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
}
}
然后我将它添加到 bundle 类中:
<?php
namespace AppBundle;
use AppBundle\DependencyInjection\MenuItemCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AppBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new MenuItemCompilerPass());
}
}
4。实现失败的代码
现在我想访问MenuItemCompilerPass 的process 方法中的AppHelper 服务:
/**
* Collect modules menu items.
*
* @param ContainerBuilder $container
*/
public function process(ContainerBuilder $container)
{
$stuff = $container->get('app.helper')->getStuff('something');
}
这会导致以下错误:
ReflectionException in ContainerBuilder.php line 862: Class does not exist
事实证明,当我删除时
$this->em = $this->container->get('doctrine.orm.entity_manager');
从AppHelper 中的构造函数再次运行。
谁能说出问题出在哪里?
【问题讨论】:
标签: php dependency-injection symfony