使用正则表达式在SilverStripe中路由


Routing in SilverStripe using regex

在SilverStripe中,我想创建动态路由。我试图路由的是每个符合以下模式的url:一些数字和文本用破折号分隔,并在末尾的"-tx-I-numberid"

示例:http://example.com/some-text-and-numbers-separated-with-dashes-tx-i1654766

我读过这些文档,但我想不通。

我想要一些规则,比如下面的

'$Slug-tx-i$ID' : 'TeamController'

我想知道我是否可以使用regex或其他方式来完成它。

我不知道有什么方法可以在路由系统中使用regex来实现这一点。您最好的选择是匹配"$Slug",然后在控制器中解析它。

如果控制器操作实例化第二个控制器并传递请求,则实际上可以嵌套控制器(有关更深入的示例,请参阅https://vimeo.com/album/3629143/video/143149869)。

例如:

class Controller1 extends Controller
{
    private static $allowed_actions = ['index'];
    public function index($req) {
        if (preg_match('/myregex/', $req->param('Slug'))) {
            return Controller2::create()->handleAction($request, $this->model);
        } else {
            return Controller3::create()->handleAction($request, $this->model);
        }
    }
}

您可以这样做:

public function index($request)
{
    $url = $request->param('Slug');
    $matches = array();
    if (strpos($url, '/') === false && preg_match('/^[a-z'-]+'-i([0-9]+)/i', $url, $matches)) {
        return "matched " . var_export($matches, true);
    }
    return ContentController::create()->handleRequest($request, $this->model);
}

但你必须更改路由规则,我还没有想出如何在不劫持所有URL的情况下实现这一点。

你能多解释一下你想做什么吗?也许可以用另一种方式解决这个问题。

关于:

RewriteRule ^[a-zA-Z'-]+'-i([0-9]+) /custom/$1

在.htaccess中?(它未经测试,但意味着您可以更准确地定位页面)。

也许这是一张301地图,而你真的在寻找它?