問(wèn)題描述
我正在使用 zend 框架開(kāi)發(fā)應(yīng)用程序.在應(yīng)用程序中,我必須為每個(gè)用戶提供一個(gè) URL,例如 mydomain.com/[username] 然后 public 將能夠查看他的個(gè)人資料.[username] 是特定用戶的用戶名
I am developing an application using zend framework. In the application I have to provide a URL for each user like mydomain.com/[username] then public will be able to view his profile. [username] is the username of the particular user
但是我怎樣才能做到這一點(diǎn)?我認(rèn)為在 ZF mydomain.com/username 中嘗試獲取名稱為 username 的控制器,但我應(yīng)該在此 URL 中顯示用戶配置文件,并且如果其他內(nèi)容如 mydomain.com 出現(xiàn),它必須轉(zhuǎn)到正確的控制器/控制器1
But how can I achieve this ? I think in ZF mydomain.com/username tries to get the controller with name username, but I should show user profiles in this URL and it must goes to the right controller if something else comein like mydomain.com/controller1
推薦答案
這個(gè)好像有點(diǎn)多,有幾個(gè)選項(xiàng):
This seems to come up quite a bit, there are a few options:
選項(xiàng) 1:自定義路由類
我已經(jīng)發(fā)表了一篇博客文章,其中詳細(xì)介紹了如何使用自定義路由類在 ZF 中實(shí)現(xiàn)此目的,請(qǐng)參閱:
I've put up a blog post with a detailed example of how to achieve this in ZF using a custom route class, see:
http://tfountain.co.uk/blog/2010/9/9/vanity-urls-zend-framework
這可能不是最簡(jiǎn)單的方法,但在我看來(lái)這是最好的方法,因?yàn)樗试S您像其他任何方法一樣設(shè)置用戶名路由,并且您仍然可以使用標(biāo)準(zhǔn)的 ZF URL 幫助程序和其他路由工具.
This might not be the simplest approach, but in my opinion it is the best, as it allows you to setup a username route like any other, and you can still use the standard ZF URL helpers and other routing toys.
選項(xiàng) 2:擴(kuò)展路由器
另一種方法是擴(kuò)展標(biāo)準(zhǔn) ZF 路由器,然后在做任何其他事情之前檢查用戶名路由.類似的東西:
Another approach is to extend the standard ZF router and then check for a username route before doing anything else. Something like:
class My_Router extends Zend_Controller_Router_Rewrite
{
public function route(Zend_Controller_Request_Abstract $request)
{
$pathBits = explode('/', $request->getPathInfo());
if (!empty($pathBits[0])) {
// check whether $pathBits[0] is a username here
// with a database lookup, if yes, set params and return
}
// fallback on the standard ZF router
return parent::route($request);
}
}
然后您需要告訴前端控制器使用您的路由器而不是默認(rèn)路由器,因此在您的引導(dǎo)程序中:
You then need to tell the front controller to use your router instead of the default one, so in your bootstrap:
protected function _initRoutes()
{
Zend_Controller_Front::getInstance()->setRouter(new My_Router());
}
將My"替換為您的應(yīng)用程序自己的命名空間.
replace 'My' with your application's own namespace.
如果你采用這種方法,你就不能為你的用戶名路由使用 URL 助手,如果你開(kāi)始需要添加其他自定義功能,事情會(huì)變得有點(diǎn)混亂,所以改用自定義路由類.
If you follow this approach you can't use the URL helper for your username routes, and things can become a bit messy if you start needing to add other custom functionality, so go with the custom route class instead.
這篇關(guān)于如何使用zend框架獲取像mydomain.com/username這樣的動(dòng)態(tài)URL的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!