I have been attempting to modify a clients website by allowing /slug to access both the pages and users models/controllers. I have read all of CakePHP 2 Routing book, however it does not go into detail about how to accomplish such a thing. I have tried this:
app/config/routes.php
App::uses('SlugRoute', 'Lib/Routing/Route');
Router::connect('/:slug', ['controller' => 'pages', 'action' => 'display'], ['routeClass' => 'SlugRoute', 'model' => 'Page']);
Router::connect('/:username', ['controller' => 'users', 'action' => 'view'], ['routeClass' => 'SlugRoute', 'model' => 'User']);
app/Lib/Routing/Route/SlugRoute.php
App::uses('Page', 'Model');
App::uses('User', 'Model');
App::uses('CakeRoute', 'Routing/Route');
App::uses('ClassRegistry', 'Utility');
class SlugRoute extends CakeRoute {
public function parse($url) {
$params = parent::parse($url);
if (empty($params)) {
return false;
}
$model = $this->options['model'];
$this->{$model} = ClassRegistry::init($model);
$result = $this->{$model}->find('first', [
'conditions' => [
$model.'.slug' => $params['slug'],
],
'fields' => array($model.'.id'),
'recursive' => -1,
]);
if ($result) {
$params['pass'] = array($result[$model]['id']);
print_r($params);
return $params;
}
return false;
}
}
Sadly this works for the pages, but does not work for users. I've considered modifying the params being returned and setting the controller/model, view, etc. But I do not believe this to be the proper way to do this. Any advice or solutions?