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.

Micro routing static calling

Is there a way of configuring a router in Micro() not to call custom routes statically?

I have following code:

class Micro extends \Phalcon\Mvc\Micro implements IRun {
.
.
.
public function setRoutes($file) {
        if (!file_exists($file)) {
            throw new \Exception('Unable to load routes file');
        }

        $routes = include($file);

        //print_r($this->getRouter());
        if (!empty($routes)) {
            foreach ($routes as $obj) {
                $this->map($obj['route'], $obj['handler'])->via([strtoupper($obj['method'])]);
            }
        }
    }

<routes.php>

return [[
        'method' => 'get',
        'route' => '/nal/v1.5/test/?{param}',
        'handler' => ['Controllers\TestController', 'get']
    ]]

<TestController.php>

class TestController extends \Phalcon\Mvc\Controller  {

    public function get($val){

        $r = new \stdClass();
        $r->method = 'GET';
        $r->value = $val;
        print_r($this->di);
    }
}

in <index.php>

.
.
.
$app->setRoutes($routes);
$app->run();

now when i fetch the endpoint i get following:

Strict standards: non-static method Controllers\TestController::get() should not be called statically

and

Fatal error: Using $this when not in object context



337
Accepted
answer

Hello, I've managed to fix this issue

In setRoutes function you should pass controller object and action in array instead of just string

in Micro.php

$controllerName = class_exists($obj['handler'][0]) ? $obj['handler'][0] : false;
if (!$controllerName) {
    throw new \Exception("Wrong controller name in routes ({$obj['handler'][0]})");
}

$controller = new $controllerName;
$controllerAction = $obj['handler'][1];

switch($obj['method']) {
    case 'get':
        $this->get($obj['route'], array($controller, $controllerAction));
        break;
    case 'post':
        $this->post($obj['route'], array($controller, $controllerAction));
        break;
    // ....                               
}

Works like a charm. Thanks.

dali

Hello, I've managed to fix this issue

In setRoutes function you should pass controller object and action in array instead of just string

in Micro.php

```php

$controllerName = class_exists($obj['handler'][0]) ? $obj['handler'][0] : false; if (!$controllerName) { throw new \Exception("Wrong controller name in routes ({$obj['handler'][0]})"); }

$controller = new $controllerName; $controllerAction = $obj['handler'][1];

switch($obj['method']) { case 'get': $this->get($obj['route'], array($controller, $controllerAction)); break; case 'post': $this->post($obj['route'], array($controller, $controllerAction)); break; // ....
}

```