【问题标题】:ZF2: create url aliases in routerZF2:在路由器中创建 url 别名
【发布时间】:2012-11-10 00:14:00
【问题描述】:

我是 Zend Framework 2 的新手,我想学习这个框架。我想在路由器中创建 url 别名。 例如,我在 module.config.php 中定义了类似的东西

'router' => array(
    'routes' => array(

        'home' => array(
            'type' => 'Zend\Mvc\Router\Http\Literal',
            'options' => array(
                'route'    => '/',
                'defaults' => array(
                    'controller' => 'Application\Controller\Index',
                    'action'     => 'index',
                ),
            ),
        ),
        'node' => array(
            'type'    => 'Application\Controller\AliasSegment',
            'options' => array(
                'route'    => '/node[/:id]',
                'constraints' => array(
                    'id' => '[0-9]+'
                ),
                'defaults' => array(
                    '__NAMESPACE__' => 'Application\Controller',
                    'controller'    => 'Index',
                    'action'        => 'index',
                    'id'            => '0'
                ),
            ),
            'may_terminate' => true,
        ),

    ),
),

当我输入www.myapp.local/node/1 时,它会路由到我的应用程序默认控制器中的默认操作。我想要的是一个可以处理 url 路径别名的路由器扩展。例如:

www.myapp.local/node/1 = www.myapp.local/aboutus
www.myapp.local/node/2 = www.myapp.local/company/gallery

我知道在采埃孚是可能的。以下是如何在 ZF 中实现此目的的教程链接: friendly urls 我知道这是波兰语,但我认为代码是不言自明的 :)

这个想法是使用 url helper 使用别名或普通段(node/[:id])组装有效的 url

我已经在我的 Application\Controller 文件夹中创建了 AliasSegment 类,但它显示了一个错误:

Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Application\Controller\AliasSegment' in C:\xampp\htdocs\industengine\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:450 Stack trace: #0 

我的 AliasSegment 类(不完整):

    <?php

    namespace Zend\Mvc\Router\Http;

    use Traversable;
    use Zend\Mvc\Router\Exception;
    use Zend\Stdlib\ArrayUtils;
    use Zend\Stdlib\RequestInterface as Request;

 class AliasSegment extends Segment
 {


    public function match(Request $request, $pathOffset = null)
    {


    }

 }

我一直在寻找答案几个小时,但我找不到任何东西。请至少告诉我我做错了什么,在哪里插入代码或者您知道更好的解决方案?

我不是在寻找现成的应用程序。我想学点东西,但如果您能详细告诉我答案,我将不胜感激:)

在此先感谢,对不起我的英语:)

已编辑:

我的自定义路由器现在正在工作。目前别名是硬编码的,但它可以工作。

我的 AliasSegment 类现在看起来:

<?php

namespace Application\Controller;

use Traversable;
use Zend\Mvc\Router\Exception;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\RequestInterface as Request;
use Zend\Mvc\Router\Http;

class AliasSegment extends \Zend\Mvc\Router\Http\Segment
{


    public function match(Request $request, $pathOffset = null)
    {
        $uri  = $request->getUri();
        $path = $uri->getPath();

        //sample logic here
        //for /about/gallery uri set node id to 1
        //todo: get action, controller and module from navigation        
        if($path == '/about/gallery'){
            $uri->setPath('/node/1');
            $request->setUri($uri);
        }

        return parent::match($request, $pathOffset);

    }

    protected function buildPath(array $parts, array $mergedParams, $isOptional, $hasChild)
    {

        if(isset($mergedParams['link'])){
            return $mergedParams['link'];
        }

        return parent::buildPath($parts, $mergedParams, $isOptional, $hasChild);
    }

}

在这种情况下,/about/gallery/node/1 的别名。两个地址都是正确的。 buildPath 函数正确返回别名路径。好吧,我希望这对某人有用:)

但是我想在 Zend_Navigation 中使用名为“链接”的附加参数来设置它。

我已经完成了我想要实现的 50%,但是现在我无法从我的路由器获取 Zend_Navigation。我不知道如何通过它。我想应该是这样的:

$sm = $this->getServiceLocator();
$auth = $sm->get('Navigation');

它在我的 IndexController 中有效,但在我的 AliasSegment 中无效。我需要在带有'link'参数的导航数组节点中找到。

编辑

我找到了解决方案。答案如下。

【问题讨论】:

    标签: alias zend-framework2 zend-navigation zend-router


    【解决方案1】:

    无法获取或创建 Application\Controller\AliasSegment 的实例

    如果这是控制器,那么我希望在 module.config.php 中有:

    'controllers' => array(
        'invokables' => array(
            '\Application\Controller\AliasSegment' => '\Application\Controller\AliasSegment',
        )
    ),
    

    你的类的命名空间看起来也有点奇怪:

    命名空间 Zend\Mvc\Router\Http;

    怎么样:

    namespace Application\Controller;
    

    【讨论】:

    • 谢谢我已经更改了命名空间,但它没有用,但是我已经更改了一些东西,它确实有效!使用 invokables 是不必要的,没有它就可以工作。我已经编辑了我的问题,所以请看这个:)
    【解决方案2】:

    好的,我成功了。此线程的重要内容: ZF2: How to get Zend\Navigation inside custom route?.

    您可以使用任何分段类型的路线。但这可能需要对match 函数进行一些修改。

    如果导航的单个页面将具有“链接”参数,则 url 将转换为“链接”字符串,但其他参数将保留在其后面。只需将其视为当前路由的默认 URI 的覆盖。

    我不得不稍微修改我的自定义路由类。首先,我必须将其命名空间更改为Application\Router。这是一个完整的课程:

    // EDIT - file within ModuleName/src/Router/Alias.php
    namespace Application\Router;
    
    use Traversable;
    use Zend\Mvc\Router\Exception;
    use Zend\Stdlib\ArrayUtils;
    use Zend\Stdlib\RequestInterface as Request;
    use Zend\Mvc\Router\Http;
    
    class Alias extends Http\Segment
    {
        private static $_navigation = null;
    
        public function match(Request $request, $pathOffset = null)
        {
            $uri  = $request->getUri();
            $path = $uri->getPath();
    
    
            $items = self::$_navigation->findAllBy('route', 'node');
            $params = null;
    
            if($items != null){
                $t = sizeof($items);
                for ($i=0; $i < $t; $i++) { 
                    $item = $items[$i];
                    $params = $item->getParams();
                    if (isset($params['link']) && $params['link']==$path){
                        $uri->setPath('/'.$item->getRoute().'/'.$params['id']);
                        $request->setUri($uri);
                        break;
                    }
                }
            }
    
            return parent::match($request, $pathOffset);
        }
    
        public function setNavigation($navigation){
            self::$_navigation = $navigation;
        }
    
        protected function buildPath(array $parts, 
                                     array $mergedParams, $isOptional, $hasChild)
        {
    
            if(isset($mergedParams['link'])){
                return $mergedParams['link'];
            }
    
            return parent::buildPath($parts, $mergedParams, 
                                                   $isOptional, $hasChild);
        }
    
    }
    

    这是module.config.php的示例部分:

    'navigation' => array(
            // The DefaultNavigationFactory we configured in (1) uses 'default' as the sitemap key
            'default' => array(
                // And finally, here is where we define our page hierarchy
                'account' => array(
                    'label' => 'Account',
                    'route' => 'node',
                    'params' => array(
                                'id' => '2',
                                ),
                    'pages' => array(
                        'home' => array(
                            'label' => 'Dashboard',
                            'route' => 'node',
                            'params' => array(
                                        'id' => '8',
                                        'link' => '/about/gallery'
                                        ),
    
                        ),
                        'login' => array(
                            'label' => 'Sign In',
                            'route' => 'node',
                            'params' => array(
                                        'id' => '6',
                                        'link' => '/signin'
                                        ),
    
                        ),
                        'logout' => array(
                            'label' => 'Sign Out',
                            'route' => 'node',
                            'params' => array(
                                        'id' => '3',
                                        ),
                        ),
                    ),
                ),
            ),
        ),
        'router' => array(
            'routes' => array(
    
                'home' => array(
                    'type' => 'Zend\Mvc\Router\Http\Literal',
                    'options' => array(
                        'route'    => '/',
                        'defaults' => array(
                            'controller' => 'Application\Controller\Index',
                            'action'     => 'index',
                        ),
                    ),
                ),
                'node' => array(
                    'type'    => 'Application\Router\Alias',
                    'options' => array(
                        'route'    => '/node[/:id]',
                        'constraints' => array(
                            'id' => '[0-9]+'
                        ),
                        'defaults' => array(
                            '__NAMESPACE__' => 'Application\Controller',
                            'controller'    => 'Index',
                            'action'        => 'index',
                            'id'            => '0'
                        ),
                    ),
                    'may_terminate' => true,
                ),
    
            ),
        ),
    

    【讨论】:

      【解决方案3】:

      如果它仅用于 /about/about/galery 之类的路由,那么您可以简单地将文字路由与子路由一起使用

      'about' => array(
          'type' => 'literal',
          'options' => array(
              'route' => '/about',
              'defaults' => array(
                  'controller' => 'module-controller-about',
                  'action'     => 'index'
              )
          ),
          'may_terminate' => true,
          'child_routes' => array(
              'galery' => array(
                  'type' => 'literal',
                  'options' => array(
                      'route' => '/galery',
                      'defaults' => array(
                          'controller' => 'module-controller-galery'
                      )
                  )
              )
          )
      )
      

      当涉及到像 /blog/1-my-great-seo-title 这样的 URL 时,您可能必须设置一个正则表达式路由(这是最慢的,文字是最快的)。

      也许看看DASPRiDs Slides from his Router Presentation

      【讨论】:

      • 好吧,不,字面路由器还不够好。我想使用 Zend Navigation 显示链接。例如,这些链接可以是 /node/1 或 /about/gallery。所以我必须在自定义路由器中检查导航数组中是否有“链接”参数。如果是,则返回此链接,否则返回段 (node/1)。看看我的问题,我已经编辑过了。它几乎可以工作,但我不知道如何在我的自定义路由器中检查导航数组。
      猜你喜欢
      • 2014-02-19
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2021-08-20
      • 1970-01-01
      • 2011-02-18
      相关资源
      最近更新 更多