how to get dynamic URL like mydomain.com/username using zend framework

前端 未结 6 1629
孤街浪徒
孤街浪徒 2020-12-15 15:02

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

6条回答
  •  鱼传尺愫
    2020-12-15 15:39

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

    Option 1: custom route class

    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

    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.

    Option 2: extending the router

    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());
    }
    

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

    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.

提交回复
热议问题