我能够使用 Symfony2 的新 Autowiring 功能将服务注入(inject)到服务中。但是,我无法将服务注入(inject) Controller 。我没有做什么/做错了什么?
这是我的 services.yml 文件:
services:
home_controller:
class: AppBundle\Controller\HomeController
autowire: true
这是我的 ServiceConsumerDemo:
namespace AppBundle\Services;
class ServiceConsumerDemo {
private $serviceDemo;
public function __construct(ServiceDemo $serviceDemo) {
$this->serviceDemo = $serviceDemo;
}
public function getMessage(){
return $this->serviceDemo->helloWorld();
}
}
这是服务演示:
namespace AppBundle\Services;
class ServiceDemo
{
public function helloWorld(){
return "hello, world!";
}
}
这是 HomeController(有效):
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class HomeController extends Controller
{
/**
* @Route("/")
*
*/
public function indexAction(Request $request)
{
$message[0] = $this->get('service_consumer_demo')->getMessage();
return new \Symfony\Component\HttpFoundation\JsonResponse($message);
}
}
这是 HomeController,它不起作用
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Services\ServiceConsumerDemo;
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 \Symfony\Component\HttpFoundation\JsonResponse($message);
}
}
这是抛出的错误:
Catchable Fatal Error: Argument 1 passed to AppBundle\Controller\HomeController::__construct() must be an instance of AppBundle\Services\ServiceConsumerDemo, none given,
如何访问 Controller 中的服务?我知道我需要将 Controller 声明为服务。所以我在 services.yml 文件中提到了 Controller 。还有什么我需要做的吗?
最佳答案
默认情况下, Controller 不被视为服务,因此您不能对它们使用 Autowiring 。
但是,这是一个足够简单的修复 - 在带有服务定义的类(即不在类中的操作方法)上添加一个 @Route
注释。
来自documentation :
The @Route annotation on a controller class can also be used to assign the controller class to a service so that the controller resolver will instantiate the controller by fetching it from the DI container instead of calling new PostController() itself.
例如:
/**
* @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: AppBundle\Controller\AppController
autowire: true
关于php - Symfony2 - 使用 Controller Autowiring 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33857659/