Tuesday, May 7, 2013

Routing for optional controller using generic controller otherwise / Dynamic Routing.

I'd like to make an application in CakePHP which manages exercises and users results. Users and results are not important in this question.

I want to have a possibility to add an exercise with adding only a specific table and line to .ini config file. Application should route to a GenericExercisesController if specific one doesn't exists. Controller should load a GenericExerciseModel if specific doesn't exists. I'd managed with model loading and partially with routing with controller like this:

In `route.php`

    foreach(Configure::read('exercisesTables') as $exerciseName){
    if( App::import('Controller', Inflector::pluralize($exerciseName))){
    Router::connect('/exercises/'.Inflector::pluralize($exerciseName).'/:action', array('controller' => Inflector::pluralize($exerciseName)));
    }else{
    Router::connect('/exercises/'.Inflector::pluralize($exerciseName).'/:action', array('controller' => 'GenericExercises', 'fakeModel' => $exerciseName));
    }
    }

So if I want to load an exercise **Foo** I should use address:

`http://example.com/exercises/Foos/view`

And this works fine, doesn't matter if specific controller exists. 

Problem begins when I use reverse routing to generate links in views. If exercise **Foo** have specific controller this works correctly:

`print $this->Html->url(array('controller' => Inflector::pluralize($exerciseName), 'action' => 'view'));` 
produces:
`/exercises/Foos/view`

But when exercise **Bar** doesn't have specific controller then the same code produces:
`/Bars`

This causes a problem, there is no `Bars` Controller.

Temporarily I'm generating those links manually, but I don't think that this is the best solution:

`print $this->Html->url("/".Configure::read('exerciseRoutingPrefix')."/".Inflector::pluralize($exerciseName)."/view");`

Those are routes in `route.php` defined before `foreach` in order as they're in file:

    Router::connect('/', array('controller' => 'questions', 'action' => 'regulations'));
    Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
    Router::connect('/help', array('controller' => 'pages', 'action' => 'faq'));

Maybe someone of you know a better solution. Thank you for reading my question.

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments: