2017-10-16 30 views
2

在Symfony的文档,它说: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。当我这样做时,我得到一个错误“不存在的对象”($通知)。

PHP应用程序/控制台项目:通知:

我通过执行以下命令来运行该服务的服务器

在文档它说我会得到相同的实例服务,但每我执行的时间:

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

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

任何想法?

+0

这并不意味着服务在呼叫之间保持(保存),这意味着每次呼叫只会创建一个此服务的实例。因此,您可以获得一个新的,但只有一个,每个电话。 – Mitchel

+0

所以我会改变这个问题,我怎样才能设置一个持久的服务? – Minniek

+0

您可以通过将数据保存到例如数据库或会话来实现此目的。除非让php解释器无限期运行,否则你不能拥有持久的服务。 所以你可以让getNotification()方法检查一个通知是否已经存在,如果不存在,创建/加载一个并返回它。 – Mitchel

回答

1

最后我得到了一个解决方案:“这意味着,每次检索服务的时候,你会得到相同的实例”

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