Route Component for CakePHP 1.2.*
I wrote this component for a simple content management system that I was building for a customer that I will go over in another upcoming post. It can be used to create and remove routes on the fly.
/app/controllers/components/route.php
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?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; } } ?> |
Usage
If you paste this into a new document be sure and check for spaces before and after your php tags. That is something I catch a lot and if you don’t know to look for them it can be a pain to debug. After you have uploaded the route file you will need to enable it inside your controller.
Then it can be used by passing the full route to either the add or remove methods. I might rewrite this later to accept $origin and $destination instead of passing the full route. For now it just seemed like a lot of unnecessary work. Let me know what you think.
$this->Route->add("Router::connect('/foo', array('controller' => 'pages', 'action' => 'display', 'foo'));");
# To remove a route
$this->Route->remove("Router::connect('/foo', array('controller' => 'pages', 'action' => 'display', 'foo'));");












