本文介绍了在CakePHP中自动路由页面别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CakePHP框架创建CMS。通过CMS创建的每个网页都有其唯一的网址别名,具体取决于虚拟文件夹结构,例如:

I am creating a CMS using CakePHP framework. Every page created through CMS will have its unique URL alias, depending also on virtual folder structure, example:


  • www.site.com/level -1 / about-us

  • www.site.com/level-2/our-service

用户可以创建自己的网页,最初会有以下地址:
www.site.com/pages/<page_id> 和然后为其创建URL别名 www.site.com/<page_alias>

User is available to create its own page, which will initially have the following address:www.site.com/pages/<page_id> and then create URL alias for it www.site.com/<page_alias>

页别名存储在数据库。
如何配置路由以自动反映这些更改,例如,CMS用户向网站添加新页面?考虑到他还可以通过CMS更新这些别名。

Page aliases are stored in database.How can I configure Routes to reflect these changes automatically, e.g., when CMS user add new page to a website? Having in mind he can also update these aliases in the future via CMS.

路由文件具有以下

Router::connect(
    '/pages/**',
    array('controller' => 'pages', 'action' => 'show')
);

手动添加路由文件中的每个新别名是非常不方便。想象一下,一个新闻网站,将有数百个文章与他们独特的别名。
有一个优雅的解决方案吗?

Adding every new alias in routes file manually is extremely not convenient. Imagine a news website which will have hundreds of articles with their unique aliases.Is there an elegant solution for this?

推荐答案

您可以从数据库获取别名, 。此实现使用缓存来防止在每个请求上加载路由。

You can fetch the aliases from the database and put them in routes. This implementation uses caching to prevent loading the routes on every request.

$menus = ''; 
//Cache::delete('routemenus'); You can uncomment this to delete cache if you change menus 
if($menus = Cache::read('routemenus') === false){ 
    echo 'load from db'; 
    $menusModel = ClassRegistry::init('Menu'); 
    $menus = $menusModel->find('all', array('conditions' => array('parent_id' => '1'))); 
    Cache::write('routemenus', $menus); 
} 

foreach($menus as $menuitem){ 
    Router::connect('/' . $menuitem['Menu']['code'] . '/:action/*', array('controller' => $menuitem['MenuType']['code'], 'action' => 'index')); 
} 

Router::connect('/', array('controller' => 'homepage', 'action' => 'index'));

这篇关于在CakePHP中自动路由页面别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:07