CakePHP - 如何使用 slug 进行反向路由?

时间:2023-01-04
本文介绍了CakePHP - 如何使用 slug 进行反向路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我使用的是 CakePHP 1.3.我有一个产品模型.在 DB 表中还有 idslug 字段.

I am using CakePHP 1.3. I have a Product model. on the DB table among others there are id and slug fields.

如果我有一个 id:37slug:My-Product-Title 的产品,我希望产品的 URL 是:

If I have a product that is id:37 and slug:My-Product-Title I want the URL for the product to be:

products/37/My-Product-Title

products/37/My-Product-Title

代替标准:

产品/视图/37

我创建了一条如下所示的路线:

I created a route that looks like this:

Router::connect(
    '/products/:id/:slug',
    array('controller' => 'products', 'action' => 'view'),
    array('pass' => array('id'), 'id' => '[0-9]+')
);

现在我可以转到 http://server/products/37/My-Product-Title,它会将我带到正确的位置.

Now I can go to http://server/products/37/My-Product-Title and it takes me to the right place.

但是如何获得反向路由以在 $HtmlHelper->link 中自动构建正确的 URL?

But How do I get reverse routing to automatically build the correct URL in $HtmlHelper->link?

当我使用时:

echo $html->link(
    'Product 37', 
    array('controller'=>'products', 'action' => 'view', 37)
);

它仍然输出标准的products/view/37 url.

It still outputs the standard products/view/37 url.

推荐答案

我认为不可能自动完成.帮手只是一个帮手",他根据给定的参数构建链接.

I don't believe that it's possible to be done auto-magically. The helper is just an "helper" who builds the link from the given parameters.

所以最简单的方法是在链接中添加另一个参数,如下所示:

So the easiest method is to add another parameter in your link like so:

echo $html->link(
    'Product 37', 
    array('controller'=>'products', 'action' => 'view', 37, $slug)
);

其中 $slug 是来自 slug 字段的数据.

where the $slug is the data from the slug field.

可能可以实现您的想法,但是您需要非常严重地打破 MVC 模式 :)

Probably it could be done your idea, but you need to break the MVC pattern very badly :)

再次阅读您的问题,我明白了.看看应该怎么做:

Reading your question again I understood it well. See how should be done:

在您的 router.php 中添加以下规则:

in your router.php add the following rule:

Router::connect(
    '/product/*',
    array('controller' => 'products', 'action' => 'view')
);

请注意它是/product/* 而不是/products/*

Please note that it's /product/* rather than /products/*

你的链接应该是这样的:

Your link should be done like this:

echo $html->link(
    'Product 37', 
    array('controller'=>'products', 'action' => 'view', 37, 'my-product-title')
);

链接看起来像:

http://yourdomain.com/product/37/my-product-title

对我来说,你的建议是不好的做法.此外,我认为从 SEO 的角度来看总是重定向用户并不好.

For me doing your suggestion is bad practice. Also I don't think it's good from SEO point of view redirecting always the user.

这篇关于CakePHP - 如何使用 slug 进行反向路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:学习 Zend 框架的最快方法? 下一篇:生成随机 5 个字符的字符串

相关文章

最新文章