我將我的應用程序從Symfony 2.8遷移到Symfony 3.3。Symfony 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(),
];
}
但我收到此異常:
調用一個成員函數get()方法在空
我控制器延伸Symfony\Bundle\FrameworkBundle\Controller\Controller
:
/**
* {@inheritdoc}
*/
class DefaultController extends Controller
{
...
}
所以我有權訪問容器。
把一些堆放在Symfony的代碼的時候,我看到容器是否設置正確:
namespace Symfony\Component\DependencyInjection;
/**
* ContainerAware trait.
*
* @author Fabien Potencier <[email protected]>
*/
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's issue tracker。
我還沒有機會玩弄新的autowire控制器的東西。只是踢,嘗試添加調用:[[setContainer,['@service_container']]]到services.yml。不應該有必要。 – Cerad
可能的重複:[Symfony控制器無法訪問容器](https://stackoverflow.com/questions/44446763/symfony-controller-unable-to-access-container)? – ccKep
您可能希望將'composer.json'添加到問題中,以防萬一有一箇舊套件覆蓋了symfony 3.3的一部分 – ccKep