【问题标题】:Routing in my PHP MVC framework我的 PHP MVC 框架中的路由
【发布时间】:2011-12-06 22:15:57
【问题描述】:

几年来,我一直致力于开发自己的 PHP 轻量级 MVC 框架。我可能会在某个时候根据开源许可发布。

这是我一直用来处理路线的:

function routes($routes, $uriPath) {

    // Loop through every route and compare it with the URI
    foreach ($routes as $route => $actualPage) {

        // Create a route with all identifiers replaced with ([^/]+) regex syntax
        // E.g. $route_regex = shop-please/([^/]+)/moo (originally shop-please/:some_identifier/moo)
        $route_regex = preg_replace('@:[^/]+@', '([^/]+)', $route);

        // Check if URI path matches regex pattern, if so create an array of values from the URI
        if(!preg_match('@' . $route_regex . '@', $uriPath, $matches)) continue;

        // Create an array of identifiers from the route
        preg_match('@' . $route_regex . '@', $route, $identifiers);

        // Combine the identifiers with the values
        $this->request->__get = array_combine($identifiers, $matches);
        array_shift($this->request->__get);

        return $actualPage;
    }

    // We didn't find a route match
    return false;
}

$routes 是一个传递的数组,格式如下:

$routes = array(
    // route => actual page
    'page/:action/:id' => 'actualPage',
    'page/:action' => 'actualPage',
)

$uriPath 是没有前导正斜杠的 URI 路径,例如页面/更新/102

在我的页面控制器中,我可以像这样访问路由信息:

echo $this->request->__get['action'];
// update

echo $this->request->__get['id'];
// 102

我的问题本质上是“这可以简化或优化吗?”。特别强调简化正则表达式以及 preg_replace 和 preg_match 调用的数量。

【问题讨论】:

标签: php regex model-view-controller routes


【解决方案1】:

我发现在这种情况下使用正则表达式非常不明智,主要是因为没有它就可以做到。我在下面提供了一个简单的代码,它在没有正则表达式的情况下完全一样。

代码:

<?php
$routes             = array
(
    // actual path => filter
    'foo'   => array('page', ':action', ':id'),
    'bar'   => array('page', ':action')
);

/**
 * @author Gajus Kuizinas <g.kuizinas@anuary.com>
 * @copyright Anuary Ltd, http://anuary.com
 * @version 1.0.0 (2011 12 06)
 */
function ay_dispatcher($url, $routes)
{
    $final_path         = FALSE;

    $url_path           = explode('/', $url);
    $url_path_length    = count($url_path);

    foreach($routes as $original_path => $filter)
    {
        // reset the parameters every time in case there is partial match
        $parameters     = array();

        // this filter is irrelevent
        if($url_path_length <> count($filter))
        {
            continue;
        }

        foreach($filter as $i => $key)
        {
            if(strpos($key, ':') === 0)
            {
                $parameters[substr($key, 1)]    = $url_path[$i];
            }
            // this filter is irrelevent
            else if($key != $url_path[$i])
            {       
                continue 2;
            }
        }

        $final_path = $original_path;

        break;
    }

    return $final_path ? array('path' => $final_path, 'parameters' => $parameters) : FALSE;
}

die(var_dump( ay_dispatcher('page/edit', $routes), ay_dispatcher('page/edit/12', $routes), ay_dispatcher('random/invalid/url', $routes) ));

输出:

array(2) {
  ["path"]=>
  string(3) "bar"
  ["parameters"]=>
  array(1) {
    ["action"]=>
    string(4) "edit"
  }
}
array(2) {
  ["path"]=>
  string(3) "foo"
  ["parameters"]=>
  array(2) {
    ["action"]=>
    string(4) "edit"
    ["id"]=>
    string(2) "12"
  }
}
bool(false)

【讨论】:

  • 我喜欢这个解决方案!也许我应该停止如此模仿 Zend Framework。但是,可能对于初学者来说,正则表达式方法使 $routes 数组的可读性略高。
  • 将你的 $routes 转换为我的格式需要 1 行代码,例如array_map(funciton($e){ return explode('/', $e); }$your_routes).
  • @Gajus 你好。你会因为我的问题获得 300 分吗? stackoverflow.com/questions/42172228/…
猜你喜欢
  • 2011-02-05
  • 1970-01-01
  • 2011-11-11
  • 2019-07-15
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 1970-01-01
  • 2017-10-13
相关资源
最近更新 更多