2017-10-16 31 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");