在service.yml
test_product.controller:
class: MyBundle\Controller\Test\ProductController
arguments: ["@product_manager.service"]
在控制器中
class ProductController extends Controller
{
/**
* @var ProductManager
*/
private $productManager;
public function __construct(ProductManager $productManager){
$this->productManager = $productManager;
}
}
在routing.yml中
test_product_addNew:
path: /test/product/addNew
defaults: { _controller:test_product.controller:addNewAction }
我想在构造函数中使用ProductManger做一些事情,但它给了我这个错误
Catchable致命错误:传递给MyBundle \ Controller \ Test \ ProductController :: __ construct()的参数1必须是MyBundle \ Services \ ProductManager的实例,Symfony \ Bundle \ TwigBundle \ Debug \ TimedTwigEngine的实例,在...中调用第1202行的./app/cache/dev/appDevDebugProjectContainer.php并定义
我是symfony的新手,感谢任何帮助
2 回答
自 Symfony 3.3 (2017年5月发布)以来,您可以轻松地使用构造函数注入和自动装配:
保持你已经拥有的休息 .
您想了解更多有关这些功能的信息吗?检查这个post with examples .
你颠倒了服务的逻辑 .
首先,您的经理必须被定义为服务,因为您需要从控制器调用它 .
然后直接调用您的经理定义为控制器中的服务 .
而且您不需要重载__construct()方法 . 只需在需要的地方拨打
->get(any_service)
.你的路线也错了 . 您必须从命名空间定义控制器 .