【问题标题】:SilverStripe routing producing weird results with 3 or more parametersSilverStripe 路由使用 3 个或更多参数产生奇怪的结果
【发布时间】:2014-05-01 14:03:55
【问题描述】:

虽然我已经成功地为包含 $Action/$ID/$OtherID 的典型模式设置了 AjaxController,但我似乎不知道如何为 $Action + 两个以上参数设置模式。

我正在尝试处理简单的“计算器”网址,如:myajax/add/5/6/7

routes.yml

Director:
 rules:
   'myajax//$action/$a/$b/$c': 'AjaxPage_Controller'

AjaxPage.php

<?php
 class AjaxPage extends Page {
 }

 class AjaxPage_Controller extends Page_Controller {
     public static $url_handlers = array(
         'myajax/add/$a/$b/$c' => 'add',
     );
     private static $allowed_actions = array (
         'add',
     );

     public function add($request){
         $v1 = (int) $request->param('a');
         $v2 = (int) $request->param('b');
         $v3 = (int) $request->param('c');
         echo json_encode(array('result' => $v1 + $v2 + $v3));
         return;
     }

 }

然后,当我访问:myajax/add/5/6/7?debug_request=1 我看到 404 Page not found 带有以下调试信息:

Debug (line 250 of RequestHandler.php): Testing 'myajax/add/$a!/$b!/$c' with 'add/5/6/7' on AjaxPage_Controller
Debug (line 250 of RequestHandler.php): Testing '$Action//$ID/$OtherID' with 'add/5/6/7' on AjaxPage_Controller
Debug (line 258 of RequestHandler.php): Rule '$Action//$ID/$OtherID' matched to action 'handleAction' on AjaxPage_Controller. Latest request params: array ( 'Action' => 'add', 'ID' => '5', 'OtherID' => '6', )
{"result":18}
Debug (line 250 of RequestHandler.php): Testing '$Action//$ID/$OtherID' with '' on ErrorPage_Controller
Debug (line 258 of RequestHandler.php): Rule '$Action//$ID/$OtherID' matched to action 'handleAction' on ErrorPage_Controller. Latest request params: array ( 'Action' => NULL, 'ID' => NULL, 'OtherID' => NULL, )
Debug (line 184 of RequestHandler.php): Action not set; using default action method name 'index'

如您所见 - 在调试信息的中间有一个正确的结果被回显,尽管哪个框架仍在寻求回退并产生 404。

有谁知道这里发生了什么(即我在这里犯了什么样的错误)?我想我已经利用了模式中移位点// 的所有组合。每次尝试之后都是开发/构建和刷新

【问题讨论】:

    标签: controller url-routing silverstripe


    【解决方案1】:

    之所以回退到404页面是因为$Action//$ID/$OtherID只匹配add/5/6,所以7还是需要匹配的。

    至于为什么您的url_handler 不匹配,这归结为换档点的作用。我将使用您的代码尝试为您解释它。基本上,移位点的左侧被匹配消耗掉,而右侧可供下一个控制器尝试使用。

    URL myajax/add/5/6/7 首先被发送到Director。这里它匹配myajax//$action/$a/$b/$c,与$action = "add"$a = "5"$b = "6"$c = "7",没有什么可匹配的。

    由于移位点直接在myajax 之后,因此在将控制权交给AjaxPage_Controller 时,仅发送myajax 右侧的部分以进行进一步匹配。所以AjaxPage_Controller 得到add/5/6/7 来匹配。

    这与 myajax/add/$a/$b/$c 不匹配,因为它不是以文字 myajax 字符串开头,因此尝试了 RequestHandler 类上的 $Action//$ID/$OtherID 处理程序。这匹配并设置 $Action = "add"$ID = "5"$OtherID = "6",剩下 7 个。

    然后运行add 操作(您可以在调试输出中看到{"result":18})并且不返回任何内容。由于它不返回任何内容,因此没有什么可以尝试匹配 7 ,因此由于最后一个控制器尚未完全处理 URL,因此会生成 404。

    至于如何修复您的代码,我会将myajax/add/$a/$b/$c url 处理程序更改为add//$a/$b/$c,因为myajax 已经被使用并且它允许$a$b$c 到都是可选的。

    【讨论】:

    • 太棒了!就是这样。非常感谢,特别是。为了解释。
    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2015-08-31
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多