We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

how to get $request object outside a controller?

I'm writing a universal acl library for the whole site. I know how to get controllerName and actionName, but how to get the HTTP Method( GET/POST/PUT ... )? I know there's a 'getMethod ()' function in $request, but how to get the instance?



6.4k
Accepted
answer

You need a DI:

<?php

$di = new Phalcon\DI\FactoryDefault;

$method = $di['request']->getMethod();

// or

$method =  $di->get('request')->getMethod();

// or

$method = $di->getRequest()->getMethod();

// If you can't access $di, get the first and usually the only one
$di = Phalcon\DI::getDefault();

// Inside a class that extends Phalcon\DI\Injectable you can access the DI with __get() magic method
// For example in controllers
$method = $this->request->getMethod();

// And classes that implements Phalcon\DI\InjectionAwareInterface with getDI()
$di = $this->getDI();

After that, you don't need the Request object to get the HTTP method, just use $_SERVER["REQUEST_METHOD"]



5.2k

Great answer. I prefer $_SERVER["REQUEST_METHOD"].

You need a DI:

<?php

$di = new Phalcon\DI\FactoryDefault;

$method = $di['request']->getMethod();

// or

$method =  $di->get('request')->getMethod();

// or

$method = $di->getRequest()->getMethod();

// If you can't access $di, get the first and usually the only one
$di = Phalcon\DI::getDefault();

// Inside a class that extends Phalcon\DI\Injectable you can access the DI with __get() magic method
// For example in controllers
$method = $this->request->getMethod();

// And classes that implements Phalcon\DI\InjectionAwareInterface with getDI()
$di = $this->getDI();

After that, you don't need the Request object to get the HTTP method, just use $_SERVER["REQUEST_METHOD"]



7.9k

It's bad practice to use GLOBAR var, it always good if your class have object dependency instead GLOBAL var, it can help you for unit test