Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.3k
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"]



2.7k

Great answer. I prefer $SERVER["REQUESTMETHOD"].

>You need a DI: > >```php ><?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"]



6.0k

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