Skip to content

Instantly share code, notes, and snippets.

@morgan
Created July 20, 2012 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morgan/3148737 to your computer and use it in GitHub Desktop.
Save morgan/3148737 to your computer and use it in GitHub Desktop.
Stack Overflow Answer: How to add a Route to the beginning of the stack in Kohana.
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Route transparently extended. Place in "classes" directory of Kohana 3+ application or module.
*
* This is in response to Stack Overflow question:
* http://stackoverflow.com/questions/11552737/kohana-module-route-precedence
*
* @author Micheal Morgan <micheal@morgan.ly>
* @copyright (c) 2012 Micheal Morgan
* @license MIT
*/
class Route extends Kohana_Route
{
/**
* Prepend Route to beginning of stack. If name already exists further in the stack, it is
* removed.
*
* Route::prepend('default', '(<controller>(/<action>(/<id>)))')
* ->defaults(array(
* 'controller' => 'welcome'
* ));
*
* @static
* @access public
* @param string route name
* @param string URI pattern
* @param array regex patterns for route keys
* @return Route
*/
public static function prepend($name, $uri_callback = NULL, $regex = NULL)
{
// Ensure entry does not already exist so it can be added to the beginning of the stack
if (isset(Route::$_routes[$name]))
{
unset(Route::$_routes[$name]);
}
// Create reference
Route::$_routes = array_merge(array($name => NULL), Route::$_routes);
// Overwrite reference
return Route::$_routes[$name] = new Route($uri_callback, $regex);
}
}
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Route extension
*
* @group route
* @category Tests
* @author Micheal Morgan <micheal@morgan.ly>
* @copyright (c) 2012 Micheal Morgan
* @license MIT
*/
class Kohana_RouteTest extends Unittest_TestCase
{
/**
* Test hash
*
* @covers Route::prepend
* @access public
* @return void
*/
public function test_prepend()
{
// Add basic route
Route::set('route-test-1');
// Prepend route to beginning of stack
Route::prepend('route-test-2')
->defaults(array('name' => 'route-test-2'));
// Get the first route in the stack
$route = current(Route::all());
// Use default data for sampling
$defaults = $route->defaults();
// Verify Route
$this->assertEquals($defaults['name'], 'route-test-2');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment