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

Micro routing, how to access $app etc when passing in handlers as array (class/method)

I know that I can use use with a closure but I am passing them in as array('fooController', 'barFunc'). Is there any way to access $app this way or am I stuck rewriting everything as a closure?



98.9k

If your controller extends Phalcon\Mvc\Controller you can access any service as follows:

class FooController extends \Phalcon\Mvc\Controller
{
    public function barFunc()
    {
        $data = $this->request->getPost();
    }
}


2.9k
edited Oct '14

Thats what I have. This is how I am routing to it :

$this->get('/foo', ['FooController', 'barFunc']);

//In barFunc

var_dump($this);

NULL

var_dump($this->request);

PHP message: PHP Fatal error:  Using $this when not in object context in ....


98.9k
Accepted
answer

An instance must be passed:

$fooController = new FooController;
$this->get('/foo', [$fooController, 'barFunc']);


2.9k

I tried the static string as well 'Controllers/FooController::barFunc' with same result. Will try your way.



2.9k

Thats perfect thanks!



2.9k

I see where I overlooked it in the documentation. Had been using a skeleton, I'll be sure to update the project owner.