Zend Framework 路线:未知数量的参数 [英] Zend Framework route: unknown number of params

查看:25
本文介绍了Zend Framework 路线:未知数量的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 N 级类别深度编写路线.因此,通常的类别 URL 如下所示:

I'm trying to write a route for an level N category depth. So an usual category URL would look like this:

http://website/my-category/my-subcategory/my-subcategory-level3/my-subcategory-level4

它的深度未知,我的路线必须匹配所有可能的级别.我为此制定了一条路线,但无法从控制器获取所有参数.

It has an unknown depth and my route has to match all possible levels. I made a route for this, but I can't get all the params from my controller.

$routeCategory = new Zend_Controller_Router_Route_Regex(
    '(([a-z0-9-]+)/?){1,}',
        array(
            'module' => 'default',
            'controller' => 'index',
            'action' => 'index'
        ),
        array( 1 => 'path'),
        '%s'
);
$router->addRoute('category', $routeCategory);

我似乎找不到将路由匹配的参数发送到控制器的方法.如果您有更好的解决方案,我愿意接受建议!

I can't seem to find a way to send the route matched params to the controller. If you have a better solution, I'm open to suggestions!

推荐答案

我找到了一个我认为适合我需求的解决方案.我会把它贴在这里给那些最终会遇到和我一样的人.

I found a solution that I think fits my needs. I'll post it here for people who will end up in the same thing I got into.

问题:

  • 需要 N 级类别的自定义路由,例如 category/subcategory/subsubcategory/...
  • N 个类别的自定义路由 + 对象,如 category/subcategory/../page.html
  • 保留 Zend Framework 的默认路由(例如对于其他模块,admin)
  • 使用URL helper
  • 组装URL
  • need custom route for level N categories like category/subcategory/subsubcategory/...
  • custom route for N categories + object like category/subcategory/../page.html
  • preserve Zend Framework's default routing (for other modules, admin for example)
  • URL assembling with URL helper

解决方案:

  • 创建自定义路由类(我使用 Zend_Controller_Router_Route_Regex 作为起点,因此我可以从 assemble() 方法中受益)
  • create custom route class (I used Zend_Controller_Router_Route_Regex as a starting point so I can benefit from the assemble() method)

实际代码:

<?php

class App_Controller_Router_Route_Category extends Zend_Controller_Router_Route_Regex
{
    public function match($path, $partial = false)
    {
        if (!$partial) {
            $path = trim(urldecode($path), '/');
        }

        $values = explode('/', $path);
        $res = (count($values) > 0) ? 1 : 0;
        if ($res === 0) {
            return false;
        }

        /**
         * Check if first param is an actual module
         * If it's a module, let the default routing take place
         */
        $modules = array();
        $frontController = Zend_Controller_Front::getInstance();
        foreach ($frontController->getControllerDirectory() as $module => $path) {
            array_push($modules, $module);
        }

        if(in_array($values[0], $modules)) {
            return false;
        }

        if ($partial) {
            $this->setMatchedPath($values[0]);
        }

        $myValues = array();
        $myValues['cmsCategory'] = array();

        // array_filter_key()? Why isn't this in a standard PHP function set yet? :)
        foreach ($values as $i => $value) {
            if (!is_int($i)) {
                unset($values[$i]);
            } else {
                if(preg_match('/.html/', $value)) {
                    $myValues['cmsObject'] = $value;
                } else {
                    array_push($myValues['cmsCategory'], $value);
                }
            }
        }

        $values = $myValues;
        $this->_values = $values;

        $values   = $this->_getMappedValues($values);
        $defaults = $this->_getMappedValues($this->_defaults, false, true);

        $return   = $values + $defaults;

        return $return;
    }

    public function assemble($data = array(), $reset = false, $encode = false, $partial = false)
    {
        if ($this->_reverse === null) {
            require_once 'Zend/Controller/Router/Exception.php';
            throw new Zend_Controller_Router_Exception('Cannot assemble. Reversed route is not specified.');
        }

        $defaultValuesMapped  = $this->_getMappedValues($this->_defaults, true, false);
        $matchedValuesMapped  = $this->_getMappedValues($this->_values, true, false);
        $dataValuesMapped     = $this->_getMappedValues($data, true, false);

        // handle resets, if so requested (By null value) to do so
        if (($resetKeys = array_search(null, $dataValuesMapped, true)) !== false) {
            foreach ((array) $resetKeys as $resetKey) {
                if (isset($matchedValuesMapped[$resetKey])) {
                    unset($matchedValuesMapped[$resetKey]);
                    unset($dataValuesMapped[$resetKey]);
                }
            }
        }

        // merge all the data together, first defaults, then values matched, then supplied
        $mergedData = $defaultValuesMapped;
        $mergedData = $this->_arrayMergeNumericKeys($mergedData, $matchedValuesMapped);
        $mergedData = $this->_arrayMergeNumericKeys($mergedData, $dataValuesMapped);

        /**
         * Default Zend_Controller_Router_Route_Regex foreach insufficient
         * I need to urlencode values if I bump into an array
         */
        if ($encode) {
            foreach ($mergedData as $key => &$value) {
                if(is_array($value)) {
                    foreach($value as $myKey => &$myValue) {
                        $myValue = urlencode($myValue);
                    }
                } else {
                    $value = urlencode($value);
                }
            }
        }

        ksort($mergedData);

        $reverse = array();
        for($i = 0; $i < count($mergedData['cmsCategory']); $i++) {
            array_push($reverse, "%s");
        }
        if(!empty($mergedData['cmsObject'])) {
            array_push($reverse, "%s");
            $mergedData['cmsCategory'][] = $mergedData['cmsObject'];
        }

        $reverse = implode("/", $reverse);
        $return = @vsprintf($reverse, $mergedData['cmsCategory']);

        if ($return === false) {
            require_once 'Zend/Controller/Router/Exception.php';
            throw new Zend_Controller_Router_Exception('Cannot assemble. Too few arguments?');
        }

        return $return;

    }
}

用法:

路线:

$routeCategory = new App_Controller_Router_Route_Category(
        '',
        array(
            'module' => 'default',
            'controller' => 'index',
            'action' => 'index'
        ),
        array(),
        '%s'
);
$router->addRoute('category', $routeCategory);

网址助手:

echo "<br>Url: " . $this->_helper->url->url(array(
                            'module' => 'default',
                            'controller' => 'index',
                            'action' => 'index',
                            'cmsCategory' => array(
                                'first-category',
                                'subcategory',
                                'subsubcategory')
                            ), 'category');

控制器中使用 getAllParams() 的示例输出

["cmsCategory"]=>
  array(3) {
    [0]=>
    string(15) "first-category"
    [1]=>
    string(16) "subcategory"
    [2]=>
    string(17) "subsubcategory"
  }
  ["cmsObject"]=>
  string(15) "my-page.html"
  ["module"]=>
  string(7) "default"
  ["controller"]=>
  string(5) "index"
  ["action"]=>
  string(5) "index"

  • 注意 cmsObject 仅在 URL 包含类似 category/subcategory/subsubcategory/my-page.html
  • 的内容时设置

    • Note the cmsObject is set only when the URL contains something like category/subcategory/subsubcategory/my-page.html
    • 这篇关于Zend Framework 路线:未知数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆