Search code examples
zend-framework2comet

Server-sent events and ZF 2.5


I am developing an application with ZF2.5. I need to make an SSE (Server-Sent Events) module, but I can't manage to do that using a controller, it does not keep my connection alive (of the type: text/event-stream). So I am doing this in a separate php file, but I need authentication on that, and needed to reach Zend's service manager from this file "outside" the Zend environment.

Is it posible? Any suggestions?


Solution

  • Yes, you can do this from within ZF2, but it is not easy. The base of SSE is the connection is kept open. So you need somehow a while(true) or similar in php to keep the process running.

    A controller is, when the function is done, terminated and the response is sent. You have to get this logic into a controller. Next, the response handler buffers all output in ZF2 and then sends all data at once. You need to reprogram the ZF2 output buffering flow, so you can send data directly from your controller without the buffering. Because otherwise, you're while(true) loop never sends data, only when you break the loop.

    So the short answer: almost anything is possible in ZF2, including your needs. But it is not that straightforward.

    The alternative is to load the service manager in your stand-alone script. This is also perfectly possible. Using the application config and merged other configs, you need to build your complete config and provision the SM with it. Then when instantiated, you can fully utilize its system.

    Also here, only instantiating the SM can be hard. Easier here is to instantiate the application and grab the SM from it:

    $app = Zend\Mvc\Application::init(include 'config/application.config.php');
    $sm = $app->getServiceManager();
    

    Note you don't `run()' the app, only bootstrap it!