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!
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
}
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With