![](/img/trans.png)
[英]Symfony2 Service Container - Passing ordinary arguments to service constructor
[英]Symfony2: service container didn't pass to controller constructor
是的-我已经搜索了答案,并在Google上花费了几个小时。 但是麻烦仍然存在
class IndexController extends Controller\CommonController
{
private $container;
public function __construct(Container $container) {
$this->container = $container;
}
在config.yml中
shop.website.index_controller:
class: %shop.website.index_controller%
parent: shop.common.common_controller
arguments: [@service_container]
和
可捕获的致命错误:传递给Shop \\ WebSiteBundle \\ Controller \\ IndexController :: __ construct()的参数1必须实现接口Symfony \\ Component \\ DependencyInjection \\ ContainerInterface,未给定,在I:\\ sf2 \\ www \\ vendor \\ symfony \\ symfony \\ src中调用\\ Symfony \\ Bundle \\ FrameworkBundle \\ Controller \\ ControllerResolver.php在第77行并在I:\\ sf2 \\ www \\ src \\ Shop \\ WebSiteBundle \\ Controller \\ IndexController.php第13行中定义
谁能解释错误在哪里?
请在yml /注释中进行配置(导致不同类型的配置使我发疯)
提前致谢
PS>更新的代码ID
services:
shop.common.common_controller:
abstract: true
class: %shop.common.common_controller%
arguments: ["@templating"]
和
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
class CommonController
{
protected $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
相同的结果(
您如何在路由中配置控制器?
我有种感觉,您没有使用“控制器即服务”符号:
my_controller:
pattern: /
defaults: { _controller: shop.website.index_controller:indexAction }
此语法与默认路由语法不同。 在这里看看。
您不需要扩展任何其他文件/控制器。
删除首先扩展。
加:
use Symfony\Component\DependencyInjection\ContainerInterface;
更换:
Container $container
至
ContainerInterface $container
接下来是Posilbe的原因:
SF2直接调用您的类构造函数。 但是您应该说将其作为服务(将所有服务选项作为调用/参数提供)
加
/**
* @Route(service="shop.website.index_controller")
*/
class IndexController extends Controller\CommonController
{
private $container;
public function __construct(Container $container) {
$this->container = $container;
}shop.website.index_controller
并注意Matthieu Napoli的答案
为什么将容器注入控制器?
只需扩展Symfony \\ Bundle \\ FrameworkBundle \\ Controller \\ Controller,您就可以访问像这样的任何服务:
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class HelloController extends Controller
{
public function indexAction()
{
// ...
$myService = $this->get('my_service');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.