Dealing with Alias URLs in CakePHP

好久不见. 提交于 2019-12-08 20:06:32

A very interesting question. I think I would use item #3. It's not really that messy -- after all, this typically is handled by the pages controller in my stuff. That's how I'd handle it - hardcode your routes to your controllers in routes.php, then have a matchall route that will work for your promo codes. This allows you to keep legacy URLs, as well as use a lot of the standard cake stuff (you probably will just have to explicitly state each of your controllers routes, not such a chore...) Additionally, it will let you do some cool stuff with 404 errors -- you can put some logic in there to try and figure out where they were trying to go, so you can superpower your 404's.

Note: I'm making an assumption that your promo URLs are in the form of "domain.com/advert-259" or something like that (i.e. no "domain.com/adverts/advert-259'). That would be just too simple :)

Hopefully, you can use the routing with some regex. Add this to your /config/routes.php and let me know if a different regex will help :)

$controllers = Configure::listObjects('controller');

foreach ($controllers as &$value)
{
    $value = Inflector::underscore($value);
}

Router::connect('/:promo', array('controller' => 'promos', 'action' => 'process'), array('promo' => '(?!('.implode('|', $controllers).')\W+)[a-zA-Z\-_]+/?$'));

Now you can handle all your promo codes in PromosController::process().

Basically, it checks for a promo code in url, excluding those in the $controllers array (i.e. your regular routes won't be messed up).

Later on you might want to consider caching the value of Configure::listObjects() depending on the speed of your app and your requirements.

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