php – Symfony2 – 使用Controller自动连接服务
我能够使用Symfony2的新autowire功能将服务注入服务.但是,我无法将服务注入控制器.我不做什么/做错了什么?
这是我的services.yml文件: services: home_controller: class: AppBundleControllerHomeController autowire: true 这是我的ServiceConsumerDemo: namespace AppBundleServices; class ServiceConsumerDemo { private $serviceDemo; public function __construct(ServiceDemo $serviceDemo) { $this->serviceDemo = $serviceDemo; } public function getMessage(){ return $this->serviceDemo->helloWorld(); } } 这是ServiceDemo: namespace AppBundleServices; class ServiceDemo { public function helloWorld(){ return "hello,world!"; } } 这是HomeController(可以工作): namespace AppBundleController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SymfonyBundleFrameworkBundleControllerController; use SymfonyComponentHttpFoundationRequest; class HomeController extends Controller { /** * @Route("/") * */ public function indexAction(Request $request) { $message[0] = $this->get('service_consumer_demo')->getMessage(); return new SymfonyComponentHttpFoundationJsonResponse($message); } } 这是HomeController不起作用 namespace AppBundleController; use SensioBundleFrameworkExtraBundleConfigurationRoute; use SymfonyBundleFrameworkBundleControllerController; use SymfonyComponentHttpFoundationRequest; use AppBundleServicesServiceConsumerDemo; class HomeController extends Controller { private $serviceConsumerDemo; public function __construct(ServiceConsumerDemo $serviceConsumerDemo) { $this->serviceConsumerDemo = $serviceConsumerDemo; } /** * @Route("/",name="homepage") * */ public function indexAction(Request $request) { $message[0] = $this->serviceConsumerDemo->getMessage(); return new SymfonyComponentHttpFoundationJsonResponse($message); } } 这是抛出的错误:
如何访问Controller中的服务?我知道我需要将控制器声明为服务.所以我在services.yml文件中提到了控制器.还有什么我需要做的吗? 解决方法
默认情况下,控制器不被视为服务,因此您无法使用它们进行自动装配.
但是,这是一个简单的修复 – 使用服务定义在类上添加@Route注释(即不在类中的操作方法上). 从documentation:
例如: /** * @Route(service="app_controller") */ class AppController extends Controller { private $service; public function __construct(SomeService $service) { $this->service = $service; } /** @Route("/") */ public function someAction() { $this->service->doSomething(); } } 并在您的配置中: app_controller: class: AppBundleControllerAppController autowire: true (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |