問題描述
我使用的是 CakePHP 1.3.我有一個產(chǎn)品模型.在 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
的產(chǎn)品,我希望產(chǎn)品的 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
代替標(biāo)準(zhǔn):
產(chǎn)品/視圖/37
我創(chuàng)建了一條如下所示的路線:
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]+')
);
現(xiàn)在我可以轉(zhuǎn)到 http://server/products/37/My-Product-Title
,它會將我?guī)У秸_的位置.
Now I can go to http://server/products/37/My-Product-Title
and it takes me to the right place.
但是如何獲得反向路由以在 $HtmlHelper->link
中自動構(gòu)建正確的 URL?
But How do I get reverse routing to automatically build the correct URL in $HtmlHelper->link
?
當(dāng)我使用時:
echo $html->link(
'Product 37',
array('controller'=>'products', 'action' => 'view', 37)
);
它仍然輸出標(biāo)準(zhǔn)的products/view/37
url.
It still outputs the standard products/view/37
url.
推薦答案
我認為不可能自動完成.幫手只是一個幫手",他根據(jù)給定的參數(shù)構(gòu)建鏈接.
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.
所以最簡單的方法是在鏈接中添加另一個參數(shù),如下所示:
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 字段的數(shù)據(jù).
where the $slug is the data from the slug field.
可能可以實現(xiàn)您的想法,但是您需要非常嚴重地打破 MVC 模式 :)
Probably it could be done your idea, but you need to break the MVC pattern very badly :)
再次閱讀您的問題,我明白了.看看應(yīng)該怎么做:
Reading your question again I understood it well. See how should be done:
在您的 router.php 中添加以下規(guī)則:
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/*
你的鏈接應(yīng)該是這樣的:
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.
這篇關(guān)于CakePHP - 如何使用 slug 進行反向路由?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!