Symfony服务作为唯一实例

时间:2017-10-16 09:57:03

标签: symfony service

在Symfony文档中说:

“在服务容器中,默认情况下共享所有服务。这意味着每次检索服务时,您将获得相同的实例。这通常是您想要的行为,但在某些情况下,您可能需要总是得到一个新的实例。“

这是services.yml

services:
    project.notification:
    class: NotificationsBundle\Command\ServerCommand

这是班级:

class ServerCommand extends ContainerAwareCommand {

    public $notification;

    /**
     * Configure a new Command Line
     */
    protected function configure()
    {
        $this->setName('Project:notification:server') ->setDescription('Start the notification server.');
    }

    public function getNotification()
    {
        return $this->notification;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->notification = new Notification();
        $server = IoServer::factory(new HttpServer(
            new WsServer(
                $this->notification
            )
        ), 8081);

        $server->loop->addPeriodicTimer(1, function ()  {
            $this->notification->sendToAll('Hello');
        });

        $server->run();
    }
}

我想从另一个控制器获取变量$notification。当我这样做时,我收到错误“不存在的对象”($ notification)。

我通过执行以下命令来运行服务:

  

php app / console项目:通知:服务器

在文档中它说我将获得相同的实例服务,但每次执行时都会:

$this->container->get('Project.notification')->notification

我遇到了非对象错误。换句话说,我丢失了第一次运行服务时创建的对象$notification。 我需要访问用户的收集列表(它在对象$ notification中),因为我需要从另一个控制器发送消息。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

最后我得到了一个解决方案:

use WebSocket\Client;
        $client = new Client("ws://127.0.0.1:8080"); 
        $client->send("Hello from controller");