【问题标题】:Creating canonical URLs with custom route-classes使用自定义路由类创建规范 URL
【发布时间】:2011-09-02 13:21:14
【问题描述】:

我正在尝试实现规范 URL 并将其与自定义路由类结合起来。

URL 方案是这样的:

/category-x/article/123
/category-y/article/123

我创建了一个扩展 Zend_Controller_Router_Route_Regex 的自定义路由类,并检查文章 123 是否存在以及 URL 是否包含正确的类别名称。如果文章 123 属于 category-x 并且用户正在访问 category-y 我想重定向到正确的 URL。

但是路线没有任何明显的可能性可以直接执行此操作。这里的最佳实践方法是什么?

【问题讨论】:

    标签: php zend-framework routes


    【解决方案1】:

    我经常在我的动作控制器中这样做。像这样的...

    // assuming GET /category-y/article/123
    // $article->url is generated, and contains /category-x/article/123
    
    if (this->_request->getRequestUri() != $article->url) {
        return $this->_helper->redirector->goToUrl($article->url);
    }
    

    在本例中,$article->url 需要从您的数据库数据中生成。当我还拉入对象 ID 时,我经常使用它来验证正确的 slug。

    如果您想使用自定义路由类而不是使用正则表达式(您可以对其进行子类化),您也可以将其移动到您的路由类中。

    【讨论】:

      【解决方案2】:

      我最终得到了这个解决方案:

      1. 自定义路由类在其 match() 方法中创建规范 URL,如下所示:

        public function match($path, $partial = false) {
            $match = parent::match($path, $partial);
        
            if (!empty($match)) {
                 $article = $this->backend->getArticle($match['articleId']);
        
                 if (!$article) {
                     throw new Zend_Controller_Router_Exception('Article does not exist', 404);
                 }
        
                 $match['canonicalUrl'] = $this->assemble(array(
                     'title' => $article->getTitle(), 
                     'articleId' => $article->getId()
                ));
            }
        
            return $match;
        }
        

        如果 parent::match() 返回数组,则在 match() 中填充 $article。

      2. 我创建了一个前端控制器插件,它像这样连接到 routeShutdown():

        public function routeShutdown(Zend_Controller_Request_Abstract $request) {
            if ($request->has('canonicalUrl')){
                $canonicalUrl = $request->getBaseUrl() . '/' . $request->get('canonicalUrl');
        
                if ($canonicalUrl != $request->getRequestUri()) {
                    $this->getResponse()->setRedirect($canonicalUrl, 301);
                }
            }
        }
        

        它只是检查路由(自定义或原生 Zend)是否创建了规范 URL,如果请求的 URL 不匹配,则重定向到正确的规范 URL。

      【讨论】:

        猜你喜欢
        • 2017-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-09
        • 2011-10-09
        • 2022-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多