CakePHP (2.0) Dynamic URLs

喜你入骨 提交于 2019-12-11 10:24:23

问题


I'm currently looking into CakePHP 2.0 and wanting to convert old 1.3 projects to 2.0. I'm going to start from scratch because there's a whole lot of code in the projects that could be a lot better.

One of those things is the dynamic URLs, the projects multilingual and even the URLs change to the chosen language. Eg:

English: /pages/new-article Dutch: /paginas/nieuw-artikel

Both would go to PagesController::display();

Note: the URLs can be way longer, pages can have subpages and those will be added to the URL too. Eg: /pages/new-article/article-subpage

Now, the way I did it before is to have a route for everything going to a specific action. Like * going to PagesController::index();

However this seems to slow the apps down and it brings a lot of problems along with it.

So my question to you is, is there a simpler way to do this?

I do not want to hardcode anything, I should be able to change /pages/article to /page/article without needing to change the code.

Note: If you know a way to do it in 1.2 or 1.3, that would also be great, 2.0 isn't that different.


回答1:


Well i figured it out, apparently CakePHP 1.3 and 2.0 allow you to create custom route classes. It's in the documentation here: http://book.cakephp.org/2.0/en/development/routing.html?highlight=route#custom-route-classes

So basically what you need to do is create a file APP/Lib/Routing/Route/UrlRoute.php with the following contents:

class UrlRoute extends CakeRoute{

    public function parse($url){
        $params = parent::parse($url);

        # Here you get the controller and action from a database.

        // tmp
        $params['controller'] = 'pages';
        $params['action'] = 'index';

        return $params;
    }
}

And in your APP/Config/routes.php you put the following:

App::import('Lib', 'Routing/Route/UrlRoute');
Router::connect('/*', array('controller' => 'tests', 'action' => 'index'), array('routeClass' => 'UrlRoute'));

I think the real challenge is getting the arguments that usually get passed to the functions back to work. func_get_args() now returns everything behind the domain name. And retrieving the URL from the database if you're using extra params. Might have to cache each URL.



来源:https://stackoverflow.com/questions/7967296/cakephp-2-0-dynamic-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!