制作一个类似zend的路由器


Make a router like zend

我有一个url http://*.com/branch/module/view/id/1/cat/2/etc/3。

它变成了。

array
(
  'module'=>'branch',
  'controller'=>'module',
  'action'=>'view'
);

下一步我需要得到参数。我有这个数组。

/*function getNextSegments($n,$segments) {
    return array_slice ( $q = $this->segments, $n + 1 );
}
$params =   getNextSegments(3);
 */
 array ( 0 => 'id', 1 => '1', 2 => 'cat', 3 => '2', 4 => 'etc', 5 => '3' );//params

我想把它转换成这个:大堆('id'=>1,‘cat’=>2,’etc’=>3,);

我如何使用php函数来做到这一点。我知道我可以使用for或foreach,但我认为php有这样的功能,但我找不到:(。非常感谢。

  class A {
    protected function combine($params) {
        $count = count ( $params );
        $returnArray = array ();
        for($i = 0; $i < $count; $i += 2) {
            $g = $i % 2;
            if ($g == 0 or $g > 0) {
                if (isset ( $params [$i] ) and isset ( $params [$i + 1] ))
                    $returnArray [$params [$i]] = $params [$i + 1];
            }
        }
        return $returnArray;
    }
}

这很正常。如果有人对此有更好的逻辑,请帮忙。再次感谢。

PHP没有内置的函数。我只想用爆炸和循环来实现它,不应该那么难。

我在扩展的Zend_Controller_Action类中使用了这样的函数。

public function getCleanParams()
{
    $removeElements = array(
        'module' => '',
        'controller' => '',
        'action' => '',
        '_dc' => ''
    );
    return array_diff_key($this->_request->getParams(), $removeElements);
}

这将以一种干净的方式为您提供参数和您想要的格式。

您可以使用以下正则表达式(将文件命名为index.php)开始构建路由器:

<?php
$pattern = '@^(?P<module>branch)/'.
           '(?P<controller>module)/'.
           '(?P<action>view)'.
           '(:?/id[s]?/(?P<id>[0-9]+))?'.
           '(:?/cat[s]?/(?P<cat>[0-9]+))?'.
           '(:?/etc[s]?/(?P<etc>[0-9]+))?@ui';
preg_match($pattern, trim($_SERVER['REQUEST_URI'], '/'), $segment);
echo sprintf('<pre>%s</pre>', var_export($segment, true));

假设您安装了PHP5.4.x,您可以在命令行上键入以下内容:

% php -S localhost:8765

现在浏览到http://localhost:8765/branch/module/view/id/1/cat/2/etc/3

输出将为(删除数字键,0除外):

array (
  0 => 'branch/module/view/id/1/cat/2/etc/3',
  'module' => 'branch',
  'controller' => 'module',
  'action' => 'view',
  'id' => '1',
  'cat' => '2',
  'etc' => '3',
)