more refactoring for dependency injection.

This commit is contained in:
Taylor Otwell
2011-09-09 20:55:24 -05:00
parent dc1b93e2ea
commit fb811af5fc
30 changed files with 545 additions and 404 deletions

View File

@@ -14,32 +14,32 @@ class Caller {
protected $container;
/**
* The route filterer instance.
* The route filters defined for the application.
*
* @var Filterer
* @var array
*/
protected $filterer;
protected $filters;
/**
* The route delegator instance.
* The path to the application's controllers.
*
* @var Delegator
* @var string
*/
protected $delegator;
protected $path;
/**
* Create a new route caller instance.
*
* @param Container $container
* @param Filterer $filterer
* @param Delegator $delegator
* @param array $filters
* @return void
*/
public function __construct(Container $container, Filterer $filterer, Delegator $delegator)
public function __construct(Container $container, $filters, $path)
{
$this->filterer = $filterer;
$this->path = $path;
$this->filters = $filters;
$this->container = $container;
$this->delegator = $delegator;
}
/**
@@ -55,6 +55,9 @@ class Caller {
throw new \Exception('Invalid route defined for URI ['.$route->key.']');
}
// 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.
if ( ! is_null($response = $this->before($route)))
{
return $this->finish($route, $response);
@@ -62,11 +65,16 @@ class Caller {
if ( ! is_null($response = $route->call()))
{
if (is_array($response)) $response = $this->delegator->delegate($route, $response);
// If a route returns an array, it means that the route is delegating the
// handling of the request to a controller method. So, we will pass the
// array to the route delegator and let it resolve the controller.
if (is_array($response)) $response = $this->delegate($route, $response);
return $this->finish($route, $response);
}
// If we get to this point, no response was returned from the filters or the route.
// The 404 response will be returned to the browser instead of a blank screen.
return $this->finish($route, $this->container->resolve('laravel.response')->error('404'));
}
@@ -83,7 +91,88 @@ class Caller {
{
$before = array_merge(array('before'), $route->filters('before'));
return $this->filterer->filter($before, array(), true);
return $this->filter($before, array(), true);
}
/**
* Handle the delegation of a route to a controller method.
*
* @param Route $route
* @param array $delegate
* @return mixed
*/
public function delegate(Route $route, $delegate)
{
list($controller, $method) = array($delegate[0], $delegate[1]);
// A route delegate may contain an array of parameters that should be passed to
// the controller method. If it does, we will merge those parameters in with
// the other route parameters that were detected by the router.
$parameters = (isset($delegate[2])) ? array_merge((array) $delegate[2], $route->parameters) : $route->parameters;
$controller = $this->resolve($controller);
// 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 ($method == 'before' or strncmp($method, '_', 1) === 0))
{
return $this->container->resolve('laravel.response')->error('404');
}
$controller->container = $this->container;
// Again, as was the case with route closures, if the controller "before" method returns
// 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 = $controller->before();
return (is_null($response)) ? call_user_func_array(array($controller, $method), $parameters) : $response;
}
/**
* Resolve a controller name to a controller instance.
*
* @param string $controller
* @return Controller
*/
protected function resolve($controller)
{
if ( ! $this->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 ($this->container->registered('controllers.'.$controller))
{
return $this->container->resolve('controllers.'.$controller);
}
// If the controller was not registered in the container, we will instantiate
// an instance of the controller manually. All controllers are suffixed with
// "_Controller" to avoid namespacing. Allowing controllers to exist in the
// global namespace gives the developer a convenient API for using the framework.
$controller = str_replace(' ', '_', ucwords(str_replace('.', ' ', $controller))).'_Controller';
return new $controller;
}
/**
* Load the file for a given controller.
*
* @param string $controller
* @return bool
*/
protected function load($controller)
{
if (file_exists($path = $this->path.strtolower(str_replace('.', '/', $controller)).EXT))
{
require $path;
return true;
}
return false;
}
/**
@@ -99,9 +188,32 @@ class Caller {
{
if ( ! $response instanceof Response) $response = new Response($response);
$this->filterer->filter(array_merge($route->filters('after'), array('after')), array($response));
$this->filter(array_merge($route->filters('after'), array('after')), array($response));
return $response;
}
/**
* Call a filter or set of filters.
*
* @param array $filters
* @param array $parameters
* @param bool $override
* @return mixed
*/
protected function filter($filters, $parameters = array(), $override = false)
{
foreach ((array) $filters as $filter)
{
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

@@ -1,117 +0,0 @@
<?php namespace Laravel\Routing;
use Laravel\Container;
class Delegator {
/**
* The IoC container instance.
*
* @var Container
*/
protected $container;
/**
* The path to the application controllers.
*
* @var string
*/
protected $path;
/**
* Create a new route delegator instance.
*
* @param Container $container
* @param string $path
* @return void
*/
public function __construct(Container $container, $path)
{
$this->path = $path;
$this->container = $container;
}
/**
* Handle the delegation of a route to a controller method.
*
* @param Route $route
* @param array $delegate
* @return mixed
*/
public function delegate(Route $route, $delegate)
{
list($controller, $method) = array($delegate[0], $delegate[1]);
$controller = $this->resolve($controller);
// 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 ($method == 'before' or strncmp($method, '_', 1) === 0))
{
return $this->container->resolve('laravel.response')->error('404');
}
$controller->container = $this->container;
// Again, as was the case with route closures, if the controller "before" method returns
// 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 = $controller->before();
return (is_null($response)) ? call_user_func_array(array($controller, $method), $route->parameters) : $response;
}
/**
* Resolve a controller name to a controller instance.
*
* @param string $controller
* @return Controller
*/
protected function resolve($controller)
{
if ( ! $this->load($controller)) return;
if ($this->container->registered('controllers.'.$controller))
{
return $this->container->resolve('controllers.'.$controller);
}
$controller = $this->format($controller);
return new $controller;
}
/**
* Load the file for a given controller.
*
* @param string $controller
* @return bool
*/
protected function load($controller)
{
if (file_exists($path = $this->path.strtolower(str_replace('.', '/', $controller)).EXT))
{
require $path;
return true;
}
return false;
}
/**
* Format a controller name to its class name.
*
* All controllers are suffixed with "_Controller" to avoid namespacing. It gives the developer
* a more convenient environment since the controller sits in the global namespace.
*
* @param string $controller
* @return string
*/
protected function format($controller)
{
return str_replace(' ', '_', ucwords(str_replace('.', ' ', $controller))).'_Controller';
}
}

View File

@@ -1,46 +0,0 @@
<?php namespace Laravel\Routing;
class Filterer {
/**
* All of the route filters for the application.
*
* @var array
*/
protected $filters = array();
/**
* Create a new route filterer instance.
*
* @param array $filters
* @return void
*/
public function __construct($filters)
{
$this->filters = $filters;
}
/**
* Call a filter or set of filters.
*
* @param array $filters
* @param array $parameters
* @param bool $override
* @return mixed
*/
public function filter($filters, $parameters = array(), $override = false)
{
foreach ((array) $filters as $filter)
{
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

@@ -1,7 +1,6 @@
<?php namespace Laravel\Routing;
use Closure;
use Laravel\Container;
class Route {
@@ -27,7 +26,7 @@ class Route {
public $callback;
/**
* The parameters that will passed to the route function.
* The parameters that will passed to the route callback.
*
* @var array
*/
@@ -49,6 +48,29 @@ class Route {
$this->uris = $this->parse_uris($key);
}
/**
* Parse the route key and return an array of URIs the route responds to.
*
* @param string $key
* @return array
*/
protected function parse_uris($key)
{
if (strpos($key, ', ') === false) return array($this->extract_uri($key));
// 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;
};
return array_map(function($segment) use ($extractor) { return $extractor($segment); }, explode(', ', $key));
}
/**
* Call the route closure.
*
@@ -58,9 +80,7 @@ class Route {
*/
public function call()
{
if (is_null($closure = $this->find_closure())) return;
return call_user_func_array($closure, $this->parameters);
return ( ! is_null($closure = $this->closure())) ? call_user_func_array($closure, $this->parameters) : null;
}
/**
@@ -68,17 +88,15 @@ class Route {
*
* @return Closure|null
*/
protected function find_closure()
protected function closure()
{
if ($this->callback instanceof Closure) return $this->callback;
if (isset($this->callback['do'])) return $this->callback['do'];
foreach ($this->callback as $value) { if ($value instanceof Closure) return $value; }
}
/**
* Get an array of filter names defined for a route.
* Get an array of filter names defined for the route.
*
* @param string $name
* @return array
@@ -89,16 +107,14 @@ class Route {
}
/**
* Determine if the route handling has a given name.
* Determine if the route has a given name.
*
* @param string $name
* @return bool
*/
public function is($name)
{
if ( ! is_array($this->callback) or ! isset($this->callback['name'])) return false;
return $this->callback['name'] === $name;
return (is_array($this->callback) and isset($this->callback['name'])) ? $this->callback['name'] === $name : false;
}
/**
@@ -112,41 +128,6 @@ class Route {
return in_array($uri, $this->uris);
}
/**
* Parse the route key and return an array of URIs the route responds to.
*
* @param string $key
* @return array
*/
protected function parse_uris($key)
{
if (strpos($key, ', ') === false) return array($this->extract_uri($key));
foreach (explode(', ', $key) as $segment)
{
$uris[] = $this->extract_uri($segment);
}
return $uris;
}
/**
* Extract the URI from a route destination.
*
* Route destinations include the request method the route responds to, so this method
* will only remove it from the string. Unless the URI is root, the forward slash will
* be removed to make searching the URIs more convenient.
*
* @param string $segment
* @return string
*/
protected function extract_uri($segment)
{
$segment = substr($segment, strpos($segment, ' ') + 1);
return ($segment !== '/') ? trim($segment, '/') : $segment;
}
/**
* Magic Method to handle dynamic method calls to determine the name of the route.
*/

View File

@@ -11,13 +11,6 @@ class Router {
*/
public $routes;
/**
* The current request instance.
*
* @var Request
*/
protected $request;
/**
* The named routes that have been found so far.
*
@@ -35,14 +28,13 @@ class Router {
/**
* Create a new router for a request method and URI.
*
* @param Request $request
* @param array $routes
* @param array $routes
* @param string $controller_path
* @return void
*/
public function __construct(Request $request, $routes, $controller_path)
public function __construct($routes, $controller_path)
{
$this->routes = $routes;
$this->request = $request;
$this->controller_path = $controller_path;
}
@@ -74,23 +66,24 @@ class Router {
}
/**
* Search the routes for the route matching a method and URI.
* Search the routes for the route matching a request method and URI.
*
* If no route can be found, the application controllers will be searched.
*
* @param Request $request
* @return Route
*/
public function route()
public function route(Request $request)
{
// Put the request method and URI in route form. Routes begin with
// the request method and a forward slash.
$destination = $this->request->method().' /'.trim($this->request->uri(), '/');
$destination = $request->method().' /'.trim($request->uri(), '/');
// Check for a literal route match first. If we find one, there is
// no need to spin through all of the routes.
if (isset($this->routes[$destination]))
{
return $this->request->route = new Route($destination, $this->routes[$destination], array());
return $request->route = new Route($destination, $this->routes[$destination], array());
}
foreach ($this->routes as $keys => $callback)
@@ -101,17 +94,18 @@ class Router {
{
foreach (explode(', ', $keys) as $key)
{
// Append the provided formats to the route as an optional regular expression.
if ( ! is_null($formats = $this->provides($callback))) $key .= '(\.('.implode('|', $formats).'))?';
if (preg_match('#^'.$this->translate_wildcards($key).'$#', $destination))
{
return $this->request->route = new Route($keys, $callback, $this->parameters($destination, $key));
return $request->route = new Route($keys, $callback, $this->parameters($destination, $key));
}
}
}
}
return $this->request->route = $this->route_to_controller();
return $request->route = $this->route_to_controller($request, $destination);
}
/**
@@ -119,13 +113,17 @@ class Router {
*
* If no corresponding controller can be found, NULL will be returned.
*
* @param Request $request
* @param string $destination
* @return Route
*/
protected function route_to_controller()
protected function route_to_controller(Request $request, $destination)
{
if ($this->request->uri() === '/') return new Route($this->request->method().' /', function() { return array('home', 'index'); });
// If the request is to the root of the application, an ad-hoc route will be generated
// to the home controller's "index" method, making it the default controller method.
if ($request->uri() === '/') return new Route($request->method().' /', function() { return array('home', 'index'); });
$segments = explode('/', trim($this->request->uri(), '/'));
$segments = explode('/', trim($request->uri(), '/'));
if ( ! is_null($key = $this->controller_key($segments)))
{
@@ -149,7 +147,7 @@ class Router {
// were they to code the controller delegation manually.
$callback = function() use ($controller, $method) { return array($controller, $method); };
return new Route($this->request->method().' /'.$this->request->uri(), $callback, $segments);
return new Route($destination, $callback, $segments);
}
}
@@ -159,14 +157,14 @@ class Router {
*
* If a controller is found, the array key for the controller name in the URI
* segments will be returned by the method, otherwise NULL will be returned.
* The deepest possible matching controller will be considered the controller
* that should handle the request.
*
* @param array $segments
* @return int
*/
protected function controller_key($segments)
{
// Work backwards through the URI segments until we find the deepest possible
// matching controller. Once we find it, we will return those routes.
foreach (array_reverse($segments, true) as $key => $value)
{
if (file_exists($path = $this->controller_path.implode('/', array_slice($segments, 0, $key + 1)).EXT))