refactoring routing and class comments.

This commit is contained in:
Taylor Otwell
2011-10-13 21:32:11 -05:00
parent cff90b52ab
commit 9fa69e0844
27 changed files with 465 additions and 435 deletions

View File

@@ -1,194 +0,0 @@
<?php namespace Laravel\Routing;
use Closure;
use Laravel\Response;
use Laravel\Container;
use Laravel\Controller;
class Caller {
/**
* The IoC container instance.
*
* @var Container
*/
protected $container;
/**
* The route filters defined for the application.
*
* @var array
*/
protected $filters;
/**
* The path to the application's controllers.
*
* @var string
*/
protected $path;
/**
* Create a new route caller instance.
*
* @param Container $container
* @param Delegator $delegator
* @param array $filters
* @return void
*/
public function __construct(Container $container, $filters, $path)
{
$this->path = $path;
$this->filters = $filters;
$this->container = $container;
}
/**
* Call a given route and return the route's response.
*
* @param Route $route
* @return Response
*/
public function call(Route $route)
{
// Since "before" filters can halt the request cycle, we will return any response
// from the before filters. Allowing the filters to halt the request cycle makes
// common tasks like authorization convenient to implement.
$before = array_merge(array('before'), $route->filters('before'));
if ( ! is_null($response = $this->filter($before, array(), true)))
{
return $this->finish($route, $response);
}
// If a route returns a Delegate, it means the route is delegating the handling
// of the request to a controller method. We will pass the Delegate instance
// to the "delegate" method which will call the controller.
if ($route->delegates())
{
return $this->delegate($route, $route->call());
}
// If no before filters returned a response and the route is not delegating
// execution to a controller, we will call the route like normal and return
// the response. If the no response is given by the route, we will return
// the 404 error view.
elseif ( ! is_null($response = $route->call()))
{
return $this->finish($route, $response);
}
else
{
return $this->finish($route, Response::error('404'));
}
}
/**
* Handle the delegation of a route to a controller method.
*
* @param Route $route
* @param Delegate $delegate
* @return mixed
*/
protected function delegate(Route $route, Delegate $delegate)
{
// Route delegates follow a {controller}@{method} naming convention. For example,
// to delegate to the "home" controller's "index" method, the delegate should be
// formatted like "home@index". Nested controllers may be delegated to using dot
// syntax, like so: "user.profile@show".
if (strpos($delegate->destination, '@') === false)
{
throw new \Exception("Route delegate [{$delegate->destination}] has an invalid format.");
}
list($controller, $method) = explode('@', $delegate->destination);
$controller = Controller::resolve($this->container, $controller, $this->path);
// If the controller doesn't exist or the request is to an invalid method, we will
// return the 404 error response. The "before" method and any method beginning with
// an underscore are not publicly available.
if (is_null($controller) or ! $this->callable($method))
{
return Response::error('404');
}
$controller->container = $this->container;
// Again, as was the case with route closures, if the controller "before" filters
// return a response, it will be considered the response to the request and the
// controller method will not be used to handle the request to the application.
$response = $this->filter($controller->filters('before'), array(), true);
if (is_null($response))
{
$response = call_user_func_array(array($controller, $method), $route->parameters);
}
return $this->finish($controller, $response);
}
/**
* Determine if a given controller method is callable.
*
* @param string $method
* @return bool
*/
protected function callable($method)
{
return $method !== 'before' and $method !== 'after' and strncmp($method, '_', 1) !== 0;
}
/**
* Finish the route handling for the request.
*
* The route response will be converted to a Response instance and the "after" filters will be run.
*
* @param Route|Controller $destination
* @param mixed $response
* @return Response
*/
protected function finish($destination, $response)
{
if ( ! $response instanceof Response) $response = new Response($response);
$this->filter(array_merge($destination->filters('after'), array('after')), array($response));
return $response;
}
/**
* Call a filter or set of filters.
*
* @param array|string $filters
* @param array $parameters
* @param bool $override
* @return mixed
*/
protected function filter($filters, $parameters = array(), $override = false)
{
if (is_string($filters)) $filters = explode('|', $filters);
foreach ((array) $filters as $filter)
{
// Parameters may be passed into routes by specifying the list of parameters after
// a colon. If parameters are present, we will merge them into the parameter array
// that was passed to the method and slice the parameters off of the filter string.
if (($colon = strpos($filter, ':')) !== false)
{
$parameters = array_merge($parameters, explode(',', substr($filter, $colon + 1)));
$filter = substr($filter, 0, $colon);
}
if ( ! isset($this->filters[$filter])) continue;
$response = call_user_func_array($this->filters[$filter], $parameters);
// "Before" filters may override the request cycle. For example, an authentication
// filter may redirect a user to a login view if they are not logged in. Because of
// this, we will return the first filter response if overriding is enabled.
if ( ! is_null($response) and $override) return $response;
}
}
}

View File

@@ -0,0 +1,170 @@
<?php namespace Laravel\Routing;
use Laravel\IoC;
use Laravel\Response;
abstract class Controller {
/**
* The "before" filters defined for the controller.
*
* @var array
*/
public $before = array();
/**
* The "after" filters defined for the controller.
*
* @var array
*/
public $after = array();
/**
* Handle the delegation of a route to a controller method.
*
* The controller destination should follow a {controller}@{method} convention.
* Nested controllers may be delegated to using dot syntax.
*
* For example, a destination of "user.profile@show" would call the User_Profile
* controller's show method with the given parameters.
*
* @param string $destination
* @param array $parameters
* @return mixed
*/
public static function call($destination, $parameters)
{
if (strpos($destination, '@') === false)
{
throw new \Exception("Route delegate [{$destination}] has an invalid format.");
}
list($controller, $method) = explode('@', $destination);
$controller = static::resolve($controller);
if (is_null($controller) or static::hidden($method))
{
return Response::error('404');
}
// Again, as was the case with route closures, if the controller
// "before" filters return a response, it will be considered the
// response to the request and the controller method will not be
// used to handle the request to the application.
$response = Filter::run($controller->filters('before'), array(), true);
if (is_null($response))
{
$response = call_user_func_array(array($controller, $method), $parameters);
}
$filters = array_merge($controller->filters('after'), array('after'));
Filter::run($filters, array($response));
return $response;
}
/**
* Determine if a given controller method is callable.
*
* @param string $method
* @return bool
*/
protected static function hidden($method)
{
return $method == 'before' or $method == 'after' or strncmp($method, '_', 1) == 0;
}
/**
* Resolve a controller name to a controller instance.
*
* @param Container $container
* @param string $controller
* @return Controller
*/
public static function resolve($controller)
{
if ( ! static::load($controller)) return;
// If the controller is registered in the IoC container, we will
// resolve it out of the container. Using constructor injection
// on controllers via the container allows more flexible and
// testable development of applications.
if (IoC::container()->registered('controllers.'.$controller))
{
return IoC::container()->resolve('controllers.'.$controller);
}
$controller = str_replace(' ', '_', ucwords(str_replace('.', ' ', $controller))).'_Controller';
return new $controller;
}
/**
* Load the file for a given controller.
*
* @param string $controller
* @return bool
*/
protected static function load($controller)
{
$controller = strtolower(str_replace('.', '/', $controller));
if (file_exists($path = CONTROLLER_PATH.$controller.EXT))
{
require $path;
return true;
}
return false;
}
/**
* Get an array of filter names defined for the destination.
*
* @param string $name
* @return array
*/
public function filters($name)
{
return (array) $this->$name;
}
/**
* Magic Method to handle calls to undefined functions on the controller.
*
* By default, the 404 response will be returned for an calls to undefined
* methods on the controller. However, this method may also be overridden
* and used as a pseudo-router by the controller.
*/
public function __call($method, $parameters)
{
return Response::error('404');
}
/**
* Dynamically resolve items from the application IoC container.
*
* <code>
* // Retrieve an object registered in the container as "mailer"
* $mailer = $this->mailer;
*
* // Equivalent call using the IoC container instance
* $mailer = IoC::container()->resolve('mailer');
* </code>
*/
public function __get($key)
{
if (IoC::container()->registered($key))
{
return IoC::container()->resolve($key);
}
throw new \Exception("Attempting to access undefined property [$key] on controller.");
}
}

View File

@@ -0,0 +1,60 @@
<?php namespace Laravel\Routing;
class Filter {
/**
* The route filters for the application.
*
* @var array
*/
protected static $filters = array();
/**
* Register an array of route filters.
*
* @param array $filters
* @return void
*/
public static function register($filters)
{
static::$filters = array_merge(static::$filters, $filters);
}
/**
* Call a filter or set of filters.
*
* @param array|string $filters
* @param array $parameters
* @param bool $override
* @return mixed
*/
public static function run($filters, $parameters = array(), $override = false)
{
if (is_string($filters)) $filters = explode('|', $filters);
foreach ((array) $filters as $filter)
{
// Parameters may be passed into routes by specifying the list of
// parameters after a colon. If parameters are present, we will
// merge them into the parameter array that was passed to the
// method and slice the parameters off of the filter string.
if (($colon = strpos($filter, ':')) !== false)
{
$parameters = array_merge($parameters, explode(',', substr($filter, $colon + 1)));
$filter = substr($filter, 0, $colon);
}
if ( ! isset(static::$filters[$filter])) continue;
$response = call_user_func_array(static::$filters[$filter], $parameters);
// "Before" filters may override the request cycle. For example,
// an authentication filter may redirect a user to a login view
// if they are not logged in. Because of this, we will return
// the first filter response if overriding is enabled.
if ( ! is_null($response) and $override) return $response;
}
}
}

View File

@@ -90,15 +90,16 @@ class Loader {
$routes = array_merge($routes, require $path);
}
// Since route files can be nested deep within the route directory, we need to
// recursively spin through each directory to find every file.
// Since route files can be nested deep within the route directory,
// we need to recursively spin through each directory
$iterator = new Iterator(new DirectoryIterator($this->nest), Iterator::SELF_FIRST);
foreach ($iterator as $file)
{
// Since some Laravel developers may place HTML files in the route directories, we will
// check for the PHP extension before merging the file. Typically, the HTML files are
// present in installations that are not using mod_rewrite and the public directory.
// Since some Laravel developers may place HTML files in the route
// directories, we will check for the PHP extension before merging
// the file. Typically, the HTML files are present in installations
// that are not using mod_rewrite and the public directory.
if (filetype($file) === 'file' and strpos($file, EXT) !== false)
{
$routes = array_merge(require $file, $routes);

View File

@@ -1,4 +1,8 @@
<?php namespace Laravel\Routing; use Closure, Laravel\Arr;
<?php namespace Laravel\Routing;
use Closure;
use Laravel\Arr;
use Laravel\Response;
class Route {
@@ -44,56 +48,96 @@ class Route {
$this->callback = $callback;
$this->parameters = $parameters;
// The extractor closure will retrieve the URI from a given route destination.
// If the request is to the root of the application, a single forward slash
// will be returned, otherwise the leading slash will be removed.
$extractor = function($segment)
{
$segment = substr($segment, strpos($segment, ' ') + 1);
return ($segment !== '/') ? trim($segment, '/') : $segment;
};
// Extract each URI out of the route key. Since the route key has the request
// method, we will extract the method off of the string. If the URI points to
// the root of the application, a single forward slash will be returned.
// Otherwise, the leading slash will be removed.
// Extract each URI from the route key. Since the route key has the
// request method, we will extract that from the string. If the URI
// points to the root of the application, a single forward slash
// will be returned.
if (strpos($key, ', ') === false)
{
$this->uris = array($extractor($this->key));
$this->uris = array($this->extract($this->key));
}
else
{
$this->uris = array_map(function($segment) use ($extractor) { return $extractor($segment); }, explode(', ', $key));
$this->uris = array_map(array($this, 'extract'), explode(', ', $key));
}
// The route callback must be either a Closure, an array, or a string. Closures
// obviously handle the requests to the route. An array can contain filters, as
// well as a Closure to handle requests to the route. A string, delegates control
// of the request to a controller method.
if ( ! $this->callback instanceof Closure and ! is_array($this->callback) and ! is_string($this->callback))
if ( ! $callback instanceof Closure and ! is_array($callback) and ! is_string($callback))
{
throw new \Exception('Invalid route defined for URI ['.$this->key.']');
}
}
/**
* Call the closure defined for the route, or get the route delegator.
* Retrieve the URI from a given route destination.
*
* @return mixed
* If the request is to the root of the application, a single slash
* will be returned, otherwise the leading slash will be removed.
*
* @param string $segment
* @return string
*/
protected function extract($segment)
{
$segment = substr($segment, strpos($segment, ' ') + 1);
return ($segment !== '/') ? trim($segment, '/') : $segment;
}
/**
* Call a given route and return the route's response.
*
* @return Response
*/
public function call()
{
// If the value defined for a route is a Closure, we simply call the closure with the
// route's parameters and return the response.
// Since "before" filters can halt the request cycle, we will return
// any response from the before filters. Allowing filters to halt the
// request cycle makes tasks like authorization convenient.
$before = array_merge(array('before'), $this->filters('before'));
if ( ! is_null($response = $this->filter($before, array(), true)))
{
return $response;
}
if ( ! is_null($response = $this->response()))
{
if ($response instanceof Delegate)
{
return $response;
}
$filters = array_merge($this->filters('after'), array('after'));
Filter::run($filters, array($response));
return $response;
}
else
{
return Response::error('404');
}
}
/**
* Call the closure defined for the route, or get the route delegator.
*
* Note that this method differs from the "call" method in that it does
* not resolve the controller or prepare the response. Delegating to
* controller's is handled by the "call" method.
*
* @return mixed
*/
protected function response()
{
if ($this->callback instanceof Closure)
{
return call_user_func_array($this->callback, $this->parameters);
}
// Otherwise, we will assume the route is an array and will return the first value with
// a key of "delegate", or the first instance of a Closure. If the value is a string, the
// route is delegating the responsibility for handling the request to a controller.
// If the route is an array we will return the first value with a
// key of "delegate", or the first instance of a Closure. If the
// value is a string, the route is delegating the responsibility
// for handling the request to a controller.
elseif (is_array($this->callback))
{
$callback = Arr::first($this->callback, function($key, $value)
@@ -101,12 +145,15 @@ class Route {
return $key == 'delegate' or $value instanceof Closure;
});
return ($callback instanceof Closure) ? call_user_func_array($callback, $this->parameters) : new Delegate($callback);
if ($callback instanceof Closure)
{
return call_user_func_array($callback, $this->parameters);
}
else
{
return new Delegate($callback);
}
}
// If a value defined for a route is a string, it means the route is delegating control
// of the request to a controller. If that is the case, we will simply return the string
// for the route caller to parse and delegate.
elseif (is_string($this->callback))
{
return new Delegate($this->callback);
@@ -129,16 +176,6 @@ class Route {
return array();
}
/**
* Deteremine if the route delegates to a controller.
*
* @return bool
*/
public function delegates()
{
return is_string($this->callback) or (is_array($this->callback) and isset($this->callback['delegate']));
}
/**
* Determine if the route has a given name.
*
@@ -147,7 +184,7 @@ class Route {
*/
public function is($name)
{
return (is_array($this->callback) and isset($this->callback['name'])) ? $this->callback['name'] === $name : false;
return is_array($this->callback) and Arr::get($this->callback, 'name') === $name;
}
/**
@@ -166,7 +203,7 @@ class Route {
*/
public function __call($method, $parameters)
{
if (strpos($method, 'is_') === 0) { return $this->is(substr($method, 3)); }
if (strpos($method, 'is_') === 0) return $this->is(substr($method, 3));
}
}