Swader
Swader

Reputation: 11597

How does one define default key=>value pair behavior on route params in Phalcon?

I would like to define the following default behavior on my routes:

Url: myapp.com/mymodule/mycontroller/myaction/q/someTerm/key/someValue/key2/anotherValue

This url should give the dispatcher the following params:

array(
    'q' => 'someTerm',
    'key' => 'someValue',
    'key2' => 'anotherValue'
):

I know it can be easily done by extending the router and implementing my own, but I was wondering if Phalcon has a default flag that switches that approach on by default.

Right now, if I apply the route

':module/:controller/:action/:params' to this URL, I get the following params:

array(
    0 => 'q',
    1 => 'someTerm',
    2 => 'key'
    ... etc
);

Which is something I don't want.

If the Phalcon router doesn't have a default flag that does this, is there an event that fires immediately before the params become available in the DI's dispatcher in the controller? I would like to manually map them into key=>value pairs at least, before they reach the controller.

Edit: I am now looking into the beforeExecuteRoute event in the controller, should do what I need. But I'd still like it if the router did this automatically - sometimes params aren't in a fixed order, or some of them just disappear (think complex search queries).

Upvotes: 1

Views: 1597

Answers (1)

twistedxtra
twistedxtra

Reputation: 2699

You can intercept the 'beforeDispatchLoop' event in the dispatcher to transform the parameters before dispatch the action:

$di['dispatcher'] = function(){

    $eventsManager = new Phalcon\Events\Manager();

    $eventsManager->attach('dispatch', function($event, $dispatcher) {
        if ($event->getType() == 'beforeDispatchLoop') {
            $keyParams = array();
            $params = $dispatcher->getParams();
            foreach ($params as $number => $value) {
                if ($number & 1) {
                    $keyParams[$params[$number - 1]] = $value;
                }
            }
            $dispatcher->setParams($keyParams);
        }
    });

    $dispatcher = new Phalcon\MVc\Dispatcher();
    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
});

Then use the transformed parameters in the controller:

class IndexController extends ControllerBase
{

    public function indexAction()
    {

        print_r($this->dispatcher->getParams());
        print_r($this->dispatcher->getParam('key'));
    }
}

Upvotes: 4

Related Questions