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
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>
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.
Routes file has the following
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'));
http://bakery.cakephp.org/articles/iworm/2010/01/10/how-to-implement-dynamic-route-in-cakephp
We need to check if the page_alias is not the original controller we intended for E.g. if you have StatesController than /states/index should refer to index function rather than a states page_alias . For this you will need to ignore the slugs with controller name or already defined route bases when saving.
Next you will have to identify that if page_alias slug exists You can extend CakeRoute for that.
Check out this http://mark-story.com/posts/view/using-custom-route-classes-in-cakephp It has a very better implementation of things you want to do .
来源:https://stackoverflow.com/questions/25641581/automatic-routing-for-page-aliases-in-cakephp