Symfony 2 错误:在非对象上调用成员函数 get() [英] Symfony 2 Error: Call to a member function get() on a non-object
问题描述
我查找了一些解决方案,但没有找到适合我的问题.
I looked up some solutions, but none of the found fit my problem.
在一个控制器中,我创建了另一个控制器的实例
In one controller i create an instance of another controller
//Controller1
$mailController = new MailController();
$mailController->newCommentMail($entity, $em);
在 MailController 中,我想生成一个 URL 并发送一封电子邮件
In the MailController i want to generate an URL and send an email
$url = $this->generateUrl('path', array('turnId' => $data->getPoi()->getId(), 'poiId' => $data->getPoi()->getTurn()->getId()));
$this->get('mailer')->send($mail);
这两行抛出以下错误:
Error: Call to a member function get() on a non-object
但我的 IDE 识别出 $this
是控制器的一个实例.
But my IDE indentifies that $this
is an instance of a controller.
生成这样的控制器实例是否有问题,或者我做错了什么?
Is there a problem with generating an instance of a Controller like that or what am i doing wrong?
推荐答案
您可以将您的控制器定义为服务,然后在另一个控制器中获取它.
You can define your controller as service, then get it in another controller.
在您的 services.yml
中将需要的控制器定义为服务:
In your services.yml
define needed controller as a service:
services:
your_service_name:
class: YourCompany\YourBundle\Controller\YourController
然后在任何控制器中,您都可以通过容器获取此服务:
Then in any controller you'll be able to get this service via container:
$yourController = $this->get('your_service_name');
<小时>
文档中有一些关于控制器即服务的有用信息
来自 OP 的说明
这个答案是完全正确的,我只是想添加一些东西,所以这个答案可以 100% 正常工作!
This answer is totally right, i just want to add something so this Answer works to 100% fine!
在我将控制器更改为服务后,服务容器丢失,参考 这个问题在这里.
After i changed the Controller to a Service the service container was missing, refering to this Question here.
要设置容器,以及SF2的全部功能,您需要在service.yml中添加一行
To set the container, and with that the fully funcionality of SF2, you need to add one line to the service.yml
services:
mail_controller:
class: YourCompany\YourBundle\Controller\YourController
calls:
- [ setContainer, [ @service_container ]]
这篇关于Symfony 2 错误:在非对象上调用成员函数 get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!