mmhan
mmhan

Reputation: 731

CakePHP - Custom Route Controller

Is there anyway for me to create dynamic custom routes? The goal is to allow users to specify any URL they want to route to any controllers/view/ structure.

If user want to create something as below:

/a_quick_brown_fox => foxes/view/42
/jumps_over        => actions/view/42
/lazy_dog          => dogs/view/42

And many others in the future without the need to edit routes.php I am unsure of a possible solution.

I wish to allow user to input something like below

Custom URL  => [        ]
Controller  => [        ]
ID for View => [        ]

I will store it in a table to allow for unique URL checking, and what not. To allow scalability for new controllers I am okay with having prefix to slugs such as /l/<slug>

I would then wish to insert some code that will retrieve the custom URL from table and allow the routing. Is it at all possible? Has anyone ever done it?

Upvotes: 2

Views: 1407

Answers (3)

Abba Bryant
Abba Bryant

Reputation: 4012

The easiest way to do this is to have the routes controller do the saving of new routes and to cache saved routes. Each time a new route is added flush the cache and save it again.

Then create a custom Route class that will pull the cache entries out and process them in the routes.php

Upvotes: 0

JohnP
JohnP

Reputation: 50009

I'm not sure whether you can define it directly into the routing system as you propose, however you could do something like this.

First define all your applications controller/actions explicitly so that your users won't overwrite them.

Then define a catch all route that will route to a controller of your choosing

//default routes
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
//other    

//custom route
Router::connect('/*', array('controller' => 'routes', 'action' => 'custom'));

Your routes_controller/custom_action will receive whatever parameters the url contains, simply do a lookup on your DB from there and redirect to the correct route defined in your database.

function custom() {
    //get values via $this->params
}

Upvotes: 1

Anh Pham
Anh Pham

Reputation: 5481

You can create custom route class, but I don't think you have access to POST data in it (you can access GET data and Cache, if that's enough). Probably the easiest way is redirect in the controller.

Upvotes: 0

Related Questions