Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Created January 26, 2013 20:15
Show Gist options
  • Select an option

  • Save jehoshua02/4644351 to your computer and use it in GitHub Desktop.

Select an option

Save jehoshua02/4644351 to your computer and use it in GitHub Desktop.
Demonstrating possible Router usage ...
<?php
namespace NoCrupht;
class Router
{
/**
* Holds array of routes
*
* @var array
*/
protected $routes = array();
/**
* Holds closure for action execution
*
* @var \Closure
*/
protected $executeClosure;
/**
* Construct method
*
* @param array $routes
* @param \Closure $executeClosure Any closure that accepts action and params
*/
public function __construct(array $routes, \Closure $executeClosure)
{
foreach ($routes as $route) {
$this->addRoute($route);
}
$this->executeClosure = $executeClosure;
}
/**
* Executes action for given url
*
* @param string $url
*/
public function execute($url)
{
$route = $this->getRoute($url);
return $this->executeClosure($route->getAction, $route->getParams($url));
}
/**
* Finds route matching url
*
* @param string $url
*
* @return \WorkoutTracker\Web\Route
*/
protected function getRoute($url)
{
foreach ($this->routes as $route) {
if ($route->isMatch($url)) {
return $route;
}
}
}
/**
* Adds route
*
* @param \WorkoutTracker\Web\Route $route
*/
protected function addRoute(Route $route)
{
$this->routes[] = $route;
}
}
<?php
// instantiate Router with array of route arrays
// perhaps a closure can be used for action execution
$router = new \NoCrupht\Router(
array(
// new Route(pattern, action, params)
new Route('/program/create', 'Program\Create'),
new Route('/program/:id/edit', 'Program\Create', array('id' => '\d+')),
),
function ($action, $params) {
$class = sprintf('\WorkoutTracker\Web\Action\%s', $action);
$object = new $class();
// this could be a chance to do other work on the object, such as injecting
// dependencies without having to pass them through the Router interface
return call_user_func_array(array($object, 'execute'), $params);
}
);
// and finally, executing an action
$router->execute('/program/create');
$router->execute('/program/1/edit');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment