Zend框架的路线:则params的数目不详

问题描述 投票:6回答:3

我试图写一个阶级N类深度的路线。因此,一个通常的分类URL应该是这样的:

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

它有一个未知的深度和我的路线必须匹配所有可能的水平。我给这个路线,但我不能让所有从我的控制器PARAMS。

$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);

我似乎无法找到一个方法来发送的路由匹配PARAMS到控制器。如果你有一个更好的解决办法,我很开放的建议!

php zend-framework zend-route
3个回答
4
投票

我发现了一个解决方案,我觉得适合我的需要。我将它张贴在这里的人谁都会在我进入同样的事情结束了。

问题:

  • 需要层级N类别,如category/subcategory/subsubcategory/...定制路线
  • 对于N类+定制路由对象像category/subcategory/../page.html
  • 保持Zend Framework的默认路由(其它模块,admin为例)
  • URL与URL帮手装配

解:

  • 创建定制路由类(I使用Zend_Controller_Router_Route_Regex为起点,所以我可以从assemble()方法中受益)

实际的代码:

<?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"
  • 请注意,只有当URL包含类似cmsObjectcategory/subcategory/subsubcategory/my-page.html设置

2
投票

我已经做到了无路线......我只排到第一个参数,然后路线的人越来越控制器内的所有PARAMS

路线:

resources.router.routes.catalog-display.route = /catalog/item/:id
resources.router.routes.catalog-display.defaults.module = catalog
resources.router.routes.catalog-display.defaults.controller = item
resources.router.routes.catalog-display.defaults.action = display

作为例子:我用这个目录,然后进入到itemController我检查$这 - 的displayAction> Request()方法 - > getParams()方法,问题是,你可以(但我认为你知道它)读取所有的方式的键/值传递的参数,可以为例如:“site.com/catalog/item/15/kind/hat/color/red/size/M”将产生一个数组为:$params['controller'=>'catalog','action'=>'display','id'=>'15','kind'=>'hat','color'=>'red','size'=>'M'];


1
投票

对于任何跨使用Zend Framework 2或Zend框架3这个问题磕磕绊绊,有哪些可以(并且可能应该)被用于OP的路线,其中有依赖于子类别的数量未知数量的参数regex route type。要使用,下面一行添加到您的路由器配置的顶部:

use Zend\Router\Http\Regex;

然后,你可以使用一个途径,如下面以匹配未知数量的类别:

'categories' => [
    'type' => Regex::class,
        'options' => [
        'regex'    => '/categories(?<sequence>(/[\w\-]+)+)',
        'defaults' => [
            'controller' => ApplicationController\Categories::class,
            'action'     => 'view',
        ],  
        'spec' => '%sequence',
    ],  
],  

上述路线将匹配以下途径:

/categories/parent-cat
/categories/parent-cat/child-cat
/categories/parent-cat/sub-child-cat
/categories/parent-cat/sub-sub-child-cat
/categories/parent-cat-2
/categories/parent-cat-2/child-cat

... 等等。类别的顺序被传递到在sequence参数的控制器。根据需要在您的控制器可以处理此参数。

© www.soinside.com 2019 - 2024. All rights reserved.