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

Dynamic converting types in router

Hello, I found method called "convert" and idea with converting parameters before using it is awesome, but I have little problem with doing it more "dynamically".

First I tried use it as it is:

$router->convert('user', function($x) {
  return Users::findFirstByUrl($x);
});

But I fast recognized that I will get "false" if user that does not exists. It'll be great if falsy values will tell that route is not possible and router simply will go ahead with searching next possible route (or just will show notFound if needed). I tried to do it on dispatcher level in this way:

$manager->attach('dispatch:beforeExecuteRoute',
    function(Event $event, Dispatcher $dispatcher) {

        // Converters
        $params = [
            'user' => function($x) {
                if($x instanceof Users)
                    return $x;
                return Users::findFirstByUrl($x);
            }
        ];

        foreach($dispatcher->getParams() as $paramName => $param) {
            if(!array_key_exists($paramName, $params))
                continue;

            $x = $params[$paramName]($param);

            if($x) {
                $dispatcher->setParam($paramName, $x);
            } else {
                // Throw that route isn't possible... go to next
                return false; //?
            }
        }
    }
);

In that way I'll (if I thinks correct) block also notFound route? So I need to check only for parameters needed and described in url pattern. Maybe I thinks incorrect but still: returning false show empty page. How to test/convert only needed parameters and/or force to tell for router to search next possible route (including notFound)?



145.0k
Accepted
answer

There is no need to do this, from phalcon 3.1.x you can use:

$di->set('dispatcher', function() {
    $dispatcher = new Phalcon\Mvc\Dispatcher();
    $dispatcher->setModelBinder(new Phalcon\Mvc\Model\Binder());

    return $dispatcher;
})

And that's it, just put your argument in action of controller like:

showAction(User $user)

And you will have here user instance. More about this - https://docs.phalcon.io/en/3.2/dispatcher#preparing-actions-inject-model-instances