我正在学习symfony 2依赖注入系统。我试图在控制器中注入Response对象。
ServiceController.php
namespace LD\LearnBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ServiceController extends Controller
{
public function indexAction(Response $response)
{
}
}
以下是services.yml文件的内容(请注意,它包含在app / config / config.yml
中services:
ld_response:
class: Symfony\Component\HttpFoundation\Response
ld_bla:
class: LD\LearnBundle\ServiceController
arguments: ["@ld_response"]
当我尝试访问ServiceController时,我得到了
Class LD\LearnBundle\Controller\Response does not exist
500 Internal Server Error - ReflectionException
我做错了什么?
答案 0 :(得分:2)
这里有两件事:
1:" Class LD \ LearnBundle \ Controller \ Response不存在"
班级不存在。您在不导入命名空间的情况下使用了Response
,因此错误消息在此处非常明确。
2:你不应该注入回应。它根本没有任何意义。响应不是服务,它是应该通过方法参数传递的值。
答案 1 :(得分:2)
以下是修复:
namespace LD\LearnBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response; // was missing
class ServiceController extends Controller
{
public function indexAction()
{
return new Response(); // The Controller is responsible of creating the Response.
}
}
通常,Class <current-namespace>\class does not exist
错误提示缺少use
语句。
我可以补充一点:
app/config/config.yml
文件中声明您的服务(创建一个特定的services.yml
文件。更好的是:在捆绑中创建它)