Routes Component

This article is also available in the following languages:
By jbcrawford
This is a component to add/remove routes directly to/from the /app/config/routes.php file.
You can use this if you are building a content management system or something else where you may not be around to manually create routes for your app.

Please keep in mind that for this to work your web server needs read/write permission to your /app/config/routes.php file. Short story short...here is the code:

Component Class:

<?php 
class RouteComponent extends Object {
    var 
$route_file '../config/routes.php';
    
    function 
initialize() {
        if (!
is_file($this->route_file)) {
            die(
'The path to your route file is wrong. Edit /app/controllers/components/route.php and fix the problem.');
        }
    }
    
    function 
add($route) {
        
$route $route."\n";
        if (
is_writable($this->route_file)) {
            
$routes file($this->route_file);
            
$new_routes '';
            foreach (
$routes as $i) {
                if (
trim($i) != '?>') {
                    
$new_routes .= $i;
                } else break;
            }
            
$handle fopen($this->route_file'w');
            if (
fwrite($handle$new_routes.$route.'?>')) {
                return 
true;
            } else return 
false;
            
fclose($handle);
        }else return 
false;
    }
    
    function 
remove($route) {
        
$route $route."\n";
        if (
is_writable($this->route_file)) {
            
$routes file($this->route_file);
            
$new_routes '';
            foreach (
$routes as $i) {
                if (
trim($i) != '?>') {
                    if (
$i != $route) {
                        
$new_routes .= $i;
                    }
                } else break;
            }
            
$handle fopen($this->route_file'w');
            if (
fwrite($handle$new_routes.'?>')) {
                return 
true;
            } else return 
false;
            
fclose($handle);
        } else return 
false;
    }

    
/* Suggested by José Pedro Saraiva */
    
function check$route ) {
        
$route $route "\n";
        if (
is_writable$this->route_file )) {
            
$routes file$this->route_file );
            
$new_routes '';
            foreach ( 
$routes as $i ) {
                if (
trim$i ) != '?>') {
                    if (
$i == $route) {
                        return 
true;
                    }
                } else
                    break;
            }
        }
        return 
false;
    }
}
?>

Usage:

Controller Class:

<?php 
// To create a new route
$route->add("Router::connect('/test', array('controller' => 'pages', 'action' => 'display', 'test'));");
// To remove a route
$route->remove("Router::connect('/test', array('controller' => 'pages', 'action' => 'display', 'test'));");
?>

Comments

  • Posted 09/28/09 09:32:37 AM
    Nice work. Got me inspired :) Anyways there are some pretty nasty flaws in your idea. Messing with routes.php file isnt good. What if some other user launches URL after you change the routing ? he will get your new route (and if he doesnt have expected creditentials thats not good). Another thing is that it doesnt work dynamically i.e. *->addRoute(....) wont work if you use Router::url or controller->redirect or any component/controller/etc using Router module beacuse it only loads on init. So u have redirect/reload etc. I'll soon post component inspired by yours that makes dynamic changes to router. Im also adding 'promote' parameter so the route will be moved to top cause cakephp stops on first found match in routes array and thats not always what we want/need. Anyways great work and tnx for idea :) greetings from Poland
  • Posted 08/24/09 01:32:54 PM
    Hello Joseph,

    William Wallace is a spammer, he had posted the similar post on several other articles. This is the reason we have decided to unpublish his comments on the bakery (which were all the same) along with the replies on the comments.

    So please don't republish his comments.

    Thank you!
  • Posted 06/05/09 11:28:19 AM
    A way to let the routes file readable is not the best solution.
    Here is an example for default Pages Controller

    first you have to create a model where you will be storing page content and name, title and whatever..

    then in routes.php file add something like this code, which lets automatically add routes to your site:
    <?php
    //Load all static pages
    App::import('Model''Page');

    $page_model = new Page();
    //where is a page slug in each record to identify route
    $pages $page_model->find('all', array('fields' => array(EHS_PAGE_SLUG)));
    unset(
    $page_model);
    foreach(
    $pages as $page) {
        
    Router::connect(
            
    "/{$page['Page']['slug']}"
            array(
                
    'controller' => 'pages'
                
    'action' => 'display'
                
    $page['Page']['slug']
            )
        );
    }
    ?>
    You can even create a pages model as actsAs(tree), then you can load tree based menu..

  • Posted 06/02/09 12:17:29 PM
    Thanks for your component! You're a life savier, been looking for something like this for a while.

    Just a small contribution, added a 'check' function to check if a given rule exists


    function check( $route )
    {
    $route = $route . "\n";
    if (is_writable( $this->route_file )) {
    $routes = file( $this->route_file );
    $new_routes = '';
    foreach ( $routes as $i ) {
    if (trim( $i ) != '?>') {
    if ($i == $route) {
    return true;
    }
    } else
    break;
    }
    }

    return false;
    }
    • Posted 06/03/09 12:25:04 AM
      Thanks for your component! You're a life savier, been looking for something like this for a while.

      Just a small contribution, added a 'check' function to check if a given rule exists

      Thanks José!
      I added your function. I hope other people can also find this helpful.
  • Posted 01/22/09 08:57:32 AM
    Hi, thank you for sharing!
    Could you please clarify the purpose of this approach?
    And why would one chose adding this, vs simply editing the file?
    • Posted 01/22/09 09:31:10 AM
      Hi, thank you for sharing!
      Could you please clarify the purpose of this approach?
      And why would one chose adding this, vs simply editing the file?

      There are several uses for the ability to create routes on the fly. For me personally I was building a content management system and I can't just jump in and edit my routes file when somebody creates a page.

Comments are closed for articles over a year old