public
Last active

Stack Overflow Answer: How to add a Route to the beginning of the stack in Kohana.

  • Download Gist
RouteTest.php
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
<?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');
}
}
route.php
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
<?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);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.