Hareesh
Hareesh

Reputation: 519

Dynamic Routing in cakephp issue

I want to use Dynamic Routing for the static pages of my site.

I have used the following code in my Routes file

$arr = ClassRegistry::init('Page');

and

$this->loadModel('Page');
$arr = $this->Page->find('all');
foreach($arr as $value)
{
   //my code
}

But it doesn't work, and shows an error like below:

ClassRegistry is not defined

Upvotes: 1

Views: 672

Answers (1)

AD7six
AD7six

Reputation: 66198

Don't do that

you've tried to put controller code in your routes file and are intending to make your site so needlessly dependent on the database. Of course, your whole site is likely dependent on the database, but by making your routes db-dependent all requests that make it to cakephp (which means, all requests that are not a static file in the webroot) need to talk to the db at least slowing things down, and if anything goes wrong with the db, your site is white page of fatal error awesomeness for all requests. This is because the routes file is loaded very early in the request handling process. The routes file is not supposed to contain any real logic - just Router::connect statements.

Alternative: Use a catchall route

If you have any pattern that you can use for your static pages, use it so that you have only one route definition. i.e.:

Router::connect('/x/*', array('controller' => 'some', 'action' => 'thing')); //eerily similar to the default static pages route

Alternative: Write a static routes file

Build, however you like, your routes logic whenever the rules for your routes change and write them to a static file. Therefore your routes.php file becomes:

<?php
... routes that don't change ...
require 'path/to/dynamic_routes_file.php';

You can use the afterSave handler for a relevant model to trigger rebuilding this dynamic routes file.

More alternatives

There are many other ways to handle this kind of thing e.g. override the error handling process to first check if there's one of these db-dependent routes to process - Or simply create a custom route class which implements literally whatever you want.

Whatever you do though - aim for the logic at run time to be as simple/cached/static as possible - don't build a system which makes all requests need to talk to the db all the time.

Upvotes: 2

Related Questions