我正在将我的应用程序从 Symfony 2.8 迁移到 Symfony 3.3。
从我的控制器内部,我有这个:
public function indexAction()
{
$email = new Email();
$form = $this->createForm(GetStartedType::class, $email, [
'action' => $this->generateUrl('get_started_end'),
'method' => 'POST',
]);
return [
'form' => $form->createView(),
];
}
但我收到了这个例外:
在 null 上调用成员函数 get()
我的控制器扩展Symfony\Bundle\FrameworkBundle\Controller\Controller
:
/**
* {@inheritdoc}
*/
class DefaultController extends Controller
{
...
}
所以我可以访问容器。
在 Symfony 的代码中放置一些转储,我看到容器设置正确:
namespace Symfony\Component\DependencyInjection;
/**
* ContainerAware trait.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
trait ContainerAwareTrait
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* Sets the container.
*
* @param ContainerInterface|null $container A ContainerInterface instance or null
*/
public function setContainer(ContainerInterface $container = null)
{
dump('Here in the ContainerAwareTrait');
dump(null === $container);
$this->container = $container;
}
}
这转储
Here in the ContainerAwareTrait
false
因此自动装配运行良好并设置了容器。
但在ControllerTrait
我有这个:
trait ControllerTrait
{
/**
* Generates a URL from the given parameters.
*
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
* @param int $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
*
* @return string The generated URL
*
* @see UrlGeneratorInterface
*/
protected function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
{
dump('Here in the ControllerTrait');
die(dump(null === $this->container));
return $this->container->get('router')->generate($route, $parameters, $referenceType);
}
...
这是转储:
Here in the ControllerTrait
true
所以这里container
是null
,这会导致错误。
任何人都可以帮我解决这个问题吗?
为什么是container
空的?
如果可能有帮助,这是services.yml
配置(Symfony 附带的默认配置):
# controllers are imported separately to make sure they're public
# and have a tag that allows actions to type-hint services
AppBundle\Controller\:
resource: '../../src/AppBundle/Controller'
public: true
tags: ['controller.service_arguments']
这个问题作为问题发布在Symfony 的问题跟踪器上。