doushijia5684 2013-04-22 15:02
浏览 72
已采纳

如何在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).

  • 写回答

1条回答 默认 最新

  • dongzhanbi0027 2013-04-22 15:25
    关注

    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'));
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错