2017-07-24 63 views
1

嗨,我有2个(或以上)控制器我的主控制器是:symfony的访问对象

class DefaultController extends Controller 
{ 
    /** 
    * @Route("/{token}") 
    */ 
    public function indexAction($token) 
    { 
     $bot = $this->container->get('telegram_bot_api'); 
     $bot->changeBot($token, 'bot'); 

     return new Response("hello word"); 
    } 
} 

我想访问另一个控制器的机器人对象,但我不希望使用forward()因为我必须创建像T1Action($bot)T2Action($bot)

我该怎么办?

回答

0

只要您有访问应用程序服务容器,你可以获取从容器中服务:

class DifferentController extends Controller 
{ 
    public function differentAction() 
    { 
     $bot = $this->container->get('telegram_bot_api'); 

     // ... 
    } 
} 

或者 - 在我看来,这将是更好的选择 - 你可以线了你控制器作为服务,并通过构造函数将bot作为依赖注入。

仅供参考,请参阅:

+0

但这种方法必须运行丝毫路径'/ {令牌}'这是电报僵尸网络挂接 –

+0

我离开了路线注解,因为我知道没有关于你的应用,也没有你的路由。如果您共享其他控制器,或者至少您想要使用相同服务的操作,这可能会有所帮助。无论如何,重点是您可以从任何有权访问容器的应用程序服务容器中获取bot。这很强大,但在测试时需要大量的嘲弄。因此,通过构造函数注入依赖关系是更好的选择(尽管如此)。 – localheinz

+0

我使我的主控制器是这样的: '$ bot = $ this-> container-> get('telegram_bot_api'); $ bot-> changeBot('310491898:AAGo2EBRaf083tH0gD8beESDhWW-1rEpMS4','bot'); \t new TestController($ bot); \t回新的响应( “你好字”);' 和我的我的TestController有这样的代码: '类扩展的TestController DefaultController { \t私人$ BOT; \t public function __construct($ bot){ \t \t $ this-> bot = $ bot; \t} \t公共功能的indexAction() { \t的var_dump($这 - > bot-> getMe()); return; } }' 是真的吗? –