CakePHP - 如何做反向路由与lug? [英] CakePHP - How to do reverse routing with slug?

查看:166
本文介绍了CakePHP - 如何做反向路由与lug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用CakePHP 1.3。我有一个产品模型。在DB表上有 id slug 字段。

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

如果我有一个 id:37 slug:My-Product-Title 产品的网址为:

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 /我的产品标题

products/37/My-Product-Title

而不是标准:


products / view / 37

products/view/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 /

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

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

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/*

您的链接应该像这样:

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 - 如何做反向路由与lug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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