Php symfony从其他控制器访问对象
嗨,我有2个(或更多)控制器我的主控制器是:Php symfony从其他控制器访问对象,php,symfony,Php,Symfony,嗨,我有2个(或更多)控制器我的主控制器是: class DefaultController extends Controller { /** * @Route("/{token}") */ public function indexAction($token) { $bot = $this->container->get('telegram_bot_api'); $bot->changeBot($to
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");
}
}
我想访问另一个控制器中的bot对象,但我不想使用forward()
,因为我必须创建类似T1Action($bot)
或T2Action($bot)
我该怎么办?只要您有权访问应用程序服务容器,就可以从容器中获取服务:
class DifferentController extends Controller
{
public function differentAction()
{
$bot = $this->container->get('telegram_bot_api');
// ...
}
}
或者——在我看来,这将是更好的选择——您可以将控制器连接为服务,并通过构造函数将bot作为依赖项注入
有关参考,请参阅:
class DifferentController extends Controller
{
public function differentAction()
{
$bot = $this->container->get('telegram_bot_api');
// ...
}
}
或者——在我看来,这将是更好的选择——您可以将控制器连接为服务,并通过构造函数将bot作为依赖项注入
有关参考,请参阅:
/{token}
下运行这是电报机器人webhookI遗漏了路由注释,因为我对您的应用程序和路由一无所知。如果您共享其他控制器,或者至少共享希望使用相同服务的操作,可能会有所帮助。无论如何,主要的一点是,您可以从应用程序服务容器的任何地方获取bot,只要您有权访问该容器。这很强大,但在测试时需要大量模拟。因此,通过构造函数注入依赖项是更好的选择(但不是判断);$bot->changeBot('310491898:aago2ebraf083th0gd8beedshww-1rEpMS4','bot');新的测试控制器($bot);返回新的响应(“hello word”)代码>在我的TestController中我有这样的代码:类TestController扩展了DefaultController{private$bot;public function\uu construct$bot{$this->bot=$bot;}公共函数indexAction(){var\u dump($this->bot getMe());return;}
这是真的吗?不确定你想要实现什么,您能详细说明一下吗?在我的应用程序方法changeBot($token)
中,使用取自url的令牌设置,如example.com/{token}
,在主控制器设置bot对象中,我需要在其他控制器中使用此对象,但此方法必须在路径/{token}下运行
这是电报机器人webhookI,我遗漏了路由注释,因为我对您的应用程序和路由一无所知。如果您共享其他控制器,或者至少共享希望使用相同服务的操作,可能会有所帮助。无论如何,主要的一点是,您可以从应用程序服务容器的任何地方获取bot,只要您有权访问该容器。这很强大,但在测试时需要大量模拟。因此,通过构造函数注入依赖项是更好的选择(但不是判断);$bot->changeBot('310491898:aago2ebraf083th0gd8beedshww-1rEpMS4','bot');新的测试控制器($bot);返回新的响应(“hello word”)代码>在我的TestController中我有这样的代码:类TestController扩展了DefaultController{private$bot;public function\uu construct$bot{$this->bot=$bot;}公共函数indexAction(){var\u dump($this->bot getMe());return;}
这是真的吗?不确定你想要实现什么,您能详细说明一下吗?在我的应用程序方法changeBot($token)
中,使用取自url的令牌设置,如example.com/{token}
,在主控制器设置bot对象中,我需要在其他控制器中使用此对象