我正在学习Symfony2,我正在向我的控制器注入服务。我收到这个错误:
Catchable Fatal Error: Argument 1 passed to Inter\DemoBundle\Controller\DataController::__construct() must be an instance of Inter\DemoBundle\Factory\ObjectFactory, none given, called in /home/tomazi/Dev/interface.test/app/cache/dev/classes.php on line 2138 and defined
我创建了一个非常基本的结构接口 - >工厂 - >控制器
我的界面:
<?php
namespace Inter\DemoBundle\Interfaces;
interface ObjectInterface {
public function create($testObject);
}
我的工厂:
<?php
namespace Inter\DemoBundle\Factory;
use Inter\DemoBundle\Interfaces\ObjectInterface;
class ObjectFactory implements ObjectInterface{
public function create($testObject)
{
$testObject = 'Hello World';
return $testObject;
}
}
我的控制器:
<?php
namespace Inter\DemoBundle\Controller;
use Inter\DemoBundle\Factory\ObjectFactory;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class DataController
{
public $object;
public function __construct(
ObjectFactory $objectFactory
){
$this->object = $objectFactory;
}
/**
* @Route("/test")
* @return ObjectFactory
*/
public function test()
{
return $this->object;
}
}
我的Services.xml:
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<!--Factory Services-->
<service id="inter.factory.object_factory"
class="Inter\DemoBundle\Factory\ObjectFactory">
</service>
<!--Controller Services-->
<service id="inter.controller" class="Inter\DemoBundle\DataController">
<argument type="service" id="inter.factory.object_factory" />
</service>
</services>
</container>
我是服务新手判断错误我在services.xml中做错了但是我找不到错误有人能看到我做错了吗?
问候
我认为注入现在正在工作但仍然会出现这些新错误:
FileLoaderImportCircularReferenceException in FileLoader.php line 97:
Circular reference detected in
"/home/tomazi/Dev/interface.test/app/config/routing_dev.yml"
("/home/tomazi/Dev/interface.test/app/config/routing_dev.yml" >
"/home/tomazi/Dev/interface.test/app/config/routing.yml" >
"/home/tomazi/Dev/interface.test/src/Inter/DemoBundle/Controller/" >
"/home/tomazi/Dev/interface.test/app/config/routing_dev.yml").
答案 0 :(得分:3)
您需要修改路由以将其称为服务。例如:
# app/config/routing.yml
hello:
path: /hello
defaults: { _controller: inter.controller:indexAction }
如果您正在使用注释
/**
* @Route("/test", service="inter.controller")
*/
public function test()
{
return $this->object;
}
答案 1 :(得分:0)
您可以通过Symfony\Bundle\FrameworkBundle\Controller\Controller
解决此问题。它是扩展ContainerAware
的基本Symfony类,因此它知道容器。
如果你这样做,你可以简单地解决所有你的家庭:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class SomeController extends Controller
{
public function someAction()
{
$someService = $this->get('some.service');
...
}
}
答案 2 :(得分:-2)
两件事:
* http://symfony.com/doc/current/cookbook/controller/service.html#referring-to-the-service