如何使用zend框架获取像mydomain.com/username这样的动态URL [英] how to get dynamic URL like mydomain.com/username using zend framework

查看:32
本文介绍了如何使用zend框架获取像mydomain.com/username这样的动态URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 zend 框架开发应用程序.在应用程序中,我必须为每个用户提供一个 URL,例如 mydomain.com/[username] 然后 public 将能够查看他的个人资料.[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

但是我怎样才能做到这一点?我认为在 ZF mydomain.com/username 中尝试获取名称为 username 的控制器,但我应该在此 URL 中显示用户配置文件,并且如果其他内容如 mydomain.com 出现,它必须转到正确的控制器/控制器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

推荐答案

这个好像有点多,有几个选项:

This seems to come up quite a bit, there are a few options:

选项 1:自定义路由类

我已经发表了一篇博客文章,其中详细介绍了如何使用自定义路由类在 ZF 中实现此目的,请参阅:

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

这可能不是最简单的方法,但在我看来这是最好的方法,因为它允许您像其他任何方法一样设置用户名路由,并且您仍然可以使用标准的 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.

选项 2:扩展路由器

另一种方法是扩展标准 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);
    }
}

然后您需要告诉前端控制器使用您的路由器而不是默认路由器,因此在您的引导程序中:

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"替换为您的应用程序自己的命名空间.

replace 'My' with your application's own namespace.

如果你采用这种方法,你就不能为你的用户名路由使用 URL 助手,如果你开始需要添加其他自定义功能,事情会变得有点混乱,所以改用自定义路由类.

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.

这篇关于如何使用zend框架获取像mydomain.com/username这样的动态URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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