[英]Symfony2 Cannot instantiate interface in dependency injection
I have a problem when I try to create a service in Symfony2. 尝试在Symfony2中创建服务时遇到问题。
This is my services.yml 这是我的services.yml
services:
Menu:
class: My\WebBundle\Classes\System\Menu
arguments: [@service_container]
This is my service Menu: 这是我的服务菜单:
namespace My\WebBundle\Classes\System;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
Class Menu{
private $container;
public function __construct(Container $container) {
$this->container = $container;
}
public function getMenu($section) {
return "hello";
}
}
When in a controller I do: 在控制器中时:
$menu = $this->get('Menu');
I get: 我得到:
FatalErrorException: Error: Cannot instantiate interface My\\WebBundle\\Classes\\System\\Menu in ...\\cache\\dev\\appDevDebugProjectContainer.php line 1522
FatalErrorException:错误:无法实例化... \\ cache \\ dev \\ appDevDebugProjectContainer.php第1522行中的接口My \\ WebBundle \\ Classes \\ System \\ Menu
Of course I cleaned cache. 当然我清理了缓存。
Change your use statement to; 将您的使用声明更改为;
use Symfony\Component\DependencyInjection\Container;
Also I would redeclare the arguments enclosing the service name in quotes. 我还要重新声明将服务名称括在引号中的参数。
services:
Menu:
class: My\WebBundle\Classes\System\Menu
arguments: ["@service_container"]
I would question why you are injecting the whole container though. 我想问一下为什么您要注入整个容器。
Why not just inject the parts you need? 为什么不只注入所需的零件?
If you are defining your controller as a service also, you can access your Menu service by injecting that into your controller. 如果还将控制器也定义为服务,则可以通过将其注入到控制器中来访问菜单服务。
EXTRA AS PER COMMENT REQUEST ; 根据评论要求额外 ;
services:
Menu:
class: My\WebBundle\Classes\System\Menu
arguments: ["@router"]
And class would look like; 课堂看起来像;
<?php
namespace My\WebBundle\Classes\System;
use Symfony\Component\Routing\RouterInterface;
Class Menu{
private $router;
public function __construct(RouterInterface $router) {
$this->router = $router;
}
public function getMenu($section) {
return "hello";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.