Skip to content

Instantly share code, notes, and snippets.

@brianally
Created July 2, 2015 20:27
Show Gist options
  • Save brianally/a3bf0eac942ca22e1b2d to your computer and use it in GitHub Desktop.
Save brianally/a3bf0eac942ca22e1b2d to your computer and use it in GitHub Desktop.
Dynamic pages with slugs for CakePHP 2.x
<?php
// app/Lib/Routing/Route/PageSlugRoute.php
//
App::uses('Page', 'Model');
App::uses('CakeRoute', 'Routing/Route');
class PageSlugRoute extends CakeRoute {
public function parse($url) {
$params = parent::parse($url);
if (empty($params)) return false;
/* Get slugs for dynamic "static" pages. These are used to create the
* routes, as well as in the controller, to set caching.
*/
$slugs = Cache::read('Page.slugs');
if (empty($slugs)) {
App::uses('Page', 'Model');
$Page = new Page();
$slugs = $Page->getSlugs();
}
//debug($slugs);
if (isset($slugs[$params['slug']])) {
$params['pass'][] = $params['slug'];
return $params;
}
return false;
}
}
// app/Config/routes.php
App::uses('PageSlugRoute', 'Lib/Routing/Route');
// add routes directly for any non-dynamic pages
Router::connect(
'/',
[
'controller' => 'pages',
'action' => 'display',
'slug' => 'about'
),
[
'slug' => 'about',
'pass' => ['slug')
)
);
Router::connect(
'/admin/pages/edit/:id',
[
'admin' => 1,
'controller' => 'pages',
'action' => 'edit'
],
[
'id' => '[0-9]+',
'pass' => ['id']
]
);
Router::connect(
'/admin/pages/add/:parent_id',
[
'admin' => 1,
'controller' => 'pages',
'action' => 'add'
],
[
'parent_id' => '[0-9]+',
'pass' => ['parent_id']
]
);
Router::connect(
'/admin/pages/delete/:id',
[
'admin' => 1,
'controller' => 'pages',
'action' => 'delete'
],
[
'id' => '[0-9]+',
'pass' => ['id']
]
);
// dynamic routes
Router::connect(
'/:slug',
[
'admin' => 0,
'controller' => 'pages',
'action' => 'display'
],
[
'slug' => '[-0-9a-z]+',
'pass' => ['slug'],
'routeClass' => 'PageSlugRoute'
]
);
CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment