How to determine if a Zend Framework 2 application is running in a console or HTTP context?

I am writing a module to perform some tasks based on whether the application is running in the console or in the context of HTTP. Is there any way to detect this when loading a module?

For example, I am trying to do this using the Module.php class.

namespace MyModule; use ... class Module { public function init(ModuleManager $mm) { if (Console context) { // do something } else { // do something with HTTP } } } 

Thanks!

+6
source share
2 answers

This is pretty easy. Just check if Request instance of Zend\Http\Request for Http and Zend\Console\Request for a console request. For instance:

 namespace Application; use Zend\Mvc\MvcEvent; use Zend\Http\Request as HttpRequest ; use Zend\Console\Request as ConsoleRequest ; class Module { public function onBootstrap(MvcEvent $e) { if ($e->getRequest() instanceof HttpRequest) { // do something important for Http } elseif($e->getRequest() instanceof ConsoleRequest ) { // do something important for Console } } } 
+21
source

You can use php_sapi_name()

Although this is not exhaustive, possible return values ​​include aolserver, apache, apache2filter, apache2handler, caudium, cgi (before PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen , thttpd, tux and webjames.

So, I would do:

 if (php_sapi_name() == 'cli') { //console } else { //not console } 
+3
source

All Articles