Harley Alexander
Harley Alexander

Reputation: 127

Dynamic pages in cakePHP

So I've been creating my first client website with cakePHP, and have run into a problem.

I'm trying to create a system similar to WordPress where you can create new pages (simply title, slug and content), and they are served up to their slug address (i.e. About will be available at mysite.com/about).

I've created my own controller & model for 'Pages' (overwriting the core pages controller), and have set up simple functions (view, admin_add, admin_delete). My model is simple, just the $name so it can connect to the db.

I'm pretty sure my problem lies in config/routes.php. Here is the code I'm currently using:

App::import('model', 'Page');
$Page = new Page();
$pages = $Page->find('list', array('fields' => array('id', 'slug')));
Router::connect('/:pages', array('controller' => 'pages'), array('Page' => implode($pages, '|')));

It just doesn't work though. When I visit an page I have (i.e. mysite.com/newpage), it tells me the newpage controller can't be found.

PLEASE HELP! I'm on a tight deadline :)

Thanks,

~harley

Upvotes: 2

Views: 2366

Answers (1)

Bryan Waters
Bryan Waters

Reputation: 636

You need to extend the Class CakeRoute. Put your custom model code in there, and then pass that class name to your route definition in routes.php

routes.php would look something like this.

App::import('Lib', 'routes/MyCustomRoute');
Router::connect('/:page', array('controller'=>'pages', 'action'=>'display'), array('routeClass' => 'MyCustomRoute'));

Then over in libs/routes/my_custom_route.php

class MyCustomRoute extends CakeRoute {
function parse($url) {
    $params = parent::parse($url);
    //import your model
    App::import('Model','Page');
    //create model object
    $Page = new Page();
    //find using $params['page'];
    if($Page->find('first', array('conditions'=>array('page.slug'=>$params['page'])))){
         //return $params if successfull match 
       return $params
    } else 
       return false;
    //return false to fall through to next route.

}

Upvotes: 4

Related Questions