Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a Zend Framework 2 application runs in console or HTTP context?

I'm writing a module to perform some tasks based on if the application is running in the console or HTTP context. Is there a way to detect this when the module is loaded?

For example, I try doing this with Module.php class.

namespace MyModule;

use ...

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

Thanks!

like image 428
peidiam Avatar asked Jan 27 '14 05:01

peidiam


2 Answers

Thats pretty easy. Just check if Request is an instance of Zend\Http\Request for Http and Zend\Console\Request for Console request. For example:

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
        }
    }  
}
like image 60
Ujjwal Ojha Avatar answered Oct 03 '22 18:10

Ujjwal Ojha


You should be able to use php_sapi_name()

Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until 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
}
like image 38
dave Avatar answered Oct 03 '22 19:10

dave