Commit fb811af5 authored by Taylor Otwell's avatar Taylor Otwell

more refactoring for dependency injection.

parent dc1b93e2
......@@ -14,11 +14,6 @@ class Benchmark {
*
* The elapsed time since setting a benchmark may checked via the "check" method.
*
* <code>
* // Set a benchmark starting time
* Benchmark::start('database');
* </code>
*
* @param string $name
* @return void
*/
......@@ -30,11 +25,6 @@ class Benchmark {
/**
* Get the elapsed time in milliseconds since starting a benchmark.
*
* <code>
* // Get the elapsed time since starting a benchmark
* $time = Benchmark::check('database');
* </code>
*
* @param string $name
* @return float
*/
......
<?php namespace Laravel\Cache;
/**
* Wrap the APC functions in a class that can be injected into driver.
* Since the APC functions are global, the driver is untestable without
* injecting a wrapper around them.
*/
class APC_Engine {
/**
* Get an item from the APC cache.
*
* @param string $key
* @return mixed
*/
public function get($key)
{
return apc_fetch($key);
}
/**
* Store an item in the APC cache.
*
* @param string $key
* @param mixed $value
* @param int $minutes
* @return void
*/
public function put($key, $value, $seconds)
{
apc_store($key, $value, $seconds);
}
/**
* Delete an item from the APC cache.
*
* @param string $key
* @return void
*/
public function forget($key)
{
apc_delete($key);
}
}
use Laravel\Proxy;
class APC extends Driver {
/**
* The APC Engine instance.
* The proxy class instance.
*
* @var APC_Engine
* @var Proxy
*/
private $apc;
......@@ -63,13 +21,14 @@ class APC extends Driver {
/**
* Create a new APC cache driver instance.
*
* @param APC_Engine $apc
* @param Proxy $proxy
* @param string $key
* @return void
*/
public function __construct(APC_Engine $apc, $key)
public function __construct(Proxy $apc, $key)
{
$this->apc = $apc;
$this->key = $key;
$this->proxy = $proxy;
}
/**
......@@ -91,7 +50,7 @@ class APC extends Driver {
*/
protected function retrieve($key)
{
return ( ! is_null($cache = $this->apc->get($this->key.$key))) ? $cache : null;
return ( ! is_null($cache = $this->proxy->apc_fetch($this->key.$key))) ? $cache : null;
}
/**
......@@ -104,7 +63,7 @@ class APC extends Driver {
*/
public function put($key, $value, $minutes)
{
$this->apc->put($this->key.$key, $value, $minutes * 60);
$this->proxy->apc_store($this->key.$key, $value, $minutes * 60);
}
/**
......@@ -115,7 +74,7 @@ class APC extends Driver {
*/
public function forget($key)
{
$this->apc->forget($this->key.$key);
$this->proxy->apc_delete($this->key.$key);
}
}
\ No newline at end of file
......@@ -18,6 +18,14 @@ abstract class Driver {
* A default value may also be specified, and will be returned in the requested
* item does not exist in the cache.
*
* <code>
* // Retrieve an item from the cache
* $name = Cache::get('name');
*
* // Retrieve an item from the cache and return a default value if it doesn't exist
* $name = Cache::get('name', 'Fred');
* </code>
*
* @param string $key
* @param mixed $default
* @param string $driver
......@@ -41,6 +49,11 @@ abstract class Driver {
/**
* Write an item to the cache for a given number of minutes.
*
* <code>
* // Store an item in the cache for 5 minutes
* Cache::put('name', 'Fred', 5);
* </code>
*
* @param string $key
* @param mixed $value
* @param int $minutes
......@@ -52,6 +65,14 @@ abstract class Driver {
* Get an item from the cache. If the item doesn't exist in the cache, store
* the default value in the cache and return it.
*
* <code>
* // Get an item from the cache and store the default value if it doesn't exist
* Cache::remember('name', 'Fred', 5);
*
* // Closures may also be used to defer retrieval of the default value
* Cache::remember('users', function() {return DB::table('users')->get();}, 5);
* </code>
*
* @param string $key
* @param mixed $default
* @param int $minutes
......
......@@ -160,25 +160,13 @@ return array(
'laravel.routing.router' => array('singleton' => true, 'resolver' => function($container)
{
return new Routing\Router($container->resolve('laravel.request'), require APP_PATH.'routes'.EXT, CONTROLLER_PATH);
return new Routing\Router(require APP_PATH.'routes'.EXT, CONTROLLER_PATH);
}),
'laravel.routing.caller' => array('resolver' => function($container)
{
return new Routing\Caller($container, $container->resolve('laravel.routing.filterer'), $container->resolve('laravel.routing.delegator'));
}),
'laravel.routing.filterer' => array('resolver' => function($container)
{
return new Routing\Filterer(require APP_PATH.'filters'.EXT);
}),
'laravel.routing.delegator' => array('resolver' => function($container)
{
return new Routing\Delegator($container, CONTROLLER_PATH);
return new Routing\Caller($container, require APP_PATH.'filters'.EXT, CONTROLLER_PATH);
}),
......@@ -206,8 +194,10 @@ return array(
}),
'laravel.validator' => array('resolver' => function($container)
'laravel.validator' => array('singleton' => true, 'resolver' => function($container)
{
require_once SYS_PATH.'validation/validator'.EXT;
return new Validation\Validator_Factory($container->resolve('laravel.lang'));
}),
......@@ -289,7 +279,7 @@ return array(
'laravel.cache.apc' => array('resolver' => function($container)
{
return new Cache\APC(new Cache\APC_Engine, $container->resolve('laravel.config')->get('cache.key'));
return new Cache\APC(new Proxy, $container->resolve('laravel.config')->get('cache.key'));
}),
......
......@@ -15,6 +15,11 @@ class IoC {
* The container is set early in the request cycle and can be access here for
* use as a service locator if dependency injection is not practical.
*
* <code>
* // Get the active container instance and call the resolve method
* $instance = IoC::container()->resolve('instance');
* </code>
*
* @return Container
*/
public static function container()
......@@ -24,6 +29,14 @@ class IoC {
/**
* Magic Method for calling methods on the active container instance.
*
* <code>
* // Call the "resolve" method on the active container instance
* $instance = IoC::resolve('instance');
*
* // Equivalent operation using the "container" method
* $instance = IoC::container()->resolve('instance');
* </code>
*/
public static function __callStatic($method, $parameters)
{
......
......@@ -26,6 +26,19 @@ abstract class Controller {
/**
* Dynamically resolve items from the application IoC container.
*
* First, "laravel." will be prefixed to the requested item to see if there is
* a matching Laravel core class in the IoC container. If there is not, we will
* check for the item in the container using the name as-is.
*
* <code>
* // Resolve the "laravel.input" instance from the IoC container
* $input = $this->input;
*
* // Resolve the "mailer" instance from the IoC container
* $mongo = $this->mailer;
* </code>
*
*/
public function __get($key)
{
......
......@@ -72,6 +72,18 @@ class Cookie {
*
* If a negative number of minutes is specified, the cookie will be deleted.
*
* Note: This method's signature is very similar to the PHP setcookie method.
* However, you simply need to pass the number of minutes for which you
* wish the cookie to be valid. No funky time calculation is required.
*
* <code>
* // Create a cookie that exists until the user closes their browser
* Cookie::put('color', 'blue');
*
* // Create a cookie that exists for 5 minutes
* Cookie::put('name', 'blue', 5);
* </code>
*
* @param string $name
* @param string $value
* @param int $minutes
......
......@@ -2,6 +2,18 @@
use Laravel\IoC;
/**
* The Laravel framework makes thorough use of dependency injection assisted by an application
* inversion of control container. This allows for great flexibility, easy testing, and better
* architecture. However, most PHP framework users may be used to accessing classes through
* a variety of static methods. Laravel provides "facades" to simulate this behavior while
* still using heavy dependency injection.
*
* Each class that is commonly used by the developer has a corresponding facade defined in
* this file. All of the various facades inherit from the abstract Facade class, which only
* has a single __callStatic magic method. The facade simply resolves the requested class
* out of the IoC container and calls the appropriate method.
*/
abstract class Facade {
/**
......
<?php namespace Laravel;
/**
* While this class may appear totally useless. It is actually quite helpful for dealing with
* the global scope of the PHP file functions. Injecting this class into the classes that need
* access to these functions allows us to test the classes without hitting the actual file system.
*/
class File {
/**
......
......@@ -7,14 +7,14 @@ class HTML {
*
* @var string
*/
public $encoding;
protected $encoding;
/**
* The URL generator instance.
*
* @var URL
*/
private $url;
protected $url;
/**
* Create a new HTML writer instance.
......@@ -278,7 +278,7 @@ class HTML {
*/
public function image($url, $alt = '', $attributes = array())
{
$attributes['alt'] = $this->entities($alt);
$attributes['alt'] = $alt;
return '<img src="'.$this->entities($this->url->to_asset($url)).'"'.$this->attributes($attributes).'>';
}
......
......@@ -31,7 +31,7 @@ class Input {
public $cookies;
/**
* Create a new Input instance.
* Create a new Input manager instance.
*
* @param Cookie $cookies
* @param array $input
......@@ -172,6 +172,14 @@ class Input {
/**
* Magic Method for retrieving items from the request input.
*
* This method is particularly helpful in controllers where access to the IoC container
* is provided through the controller's magic __get method.
*
* <code>
* // Retrieve the "name" input item from a controller method
* $name = $this->input->name;
* </code>
*/
public function __get($key)
{
......
......@@ -200,6 +200,15 @@ class Lang {
/**
* Get the string content of the language line.
*
* This provides a convenient mechanism for displaying language line in views without
* using the "get" method on the language instance.
*
* <code>
* // Display a language line by casting it to a string
* echo Lang::line('messages.welcome');
* </code>
*
*/
public function __toString()
{
......
......@@ -57,7 +57,7 @@ if ($config->get('session.driver') !== '')
// --------------------------------------------------------------
// Route the request and get the response from the route.
// --------------------------------------------------------------
$route = $container->resolve('laravel.routing.router')->route();
$route = $container->resolve('laravel.routing.router')->route($container->resolve('laravel.request'));
if ( ! is_null($route))
{
......
......@@ -39,10 +39,7 @@ class Loader {
{
$file = strtolower(str_replace('\\', '/', $class));
if (array_key_exists($class, $this->aliases))
{
return class_alias($this->aliases[$class], $class);
}
if (array_key_exists($class, $this->aliases)) return class_alias($this->aliases[$class], $class);
foreach ($this->paths as $path)
{
......
<?php namespace Laravel;
/**
* The Proxy class, like the File class, is primarily intended to get rid of
* the testability problems introduced by PHP's global functions.
*
* For instance, the APC cache driver calls the APC global functions. Instead of
* calling those functions directory in the driver, we inject a Proxy instance into
* the class, which allows us to stub the global functions.
*/
class Proxy {
/**
* Magic Method for calling any global function.
*/
public function __call($method, $parameters)
{
return call_user_func_array($method, $parameters);
}
}
\ No newline at end of file
......@@ -65,6 +65,11 @@ class Redirect extends Response {
*
* This is useful for passing status messages or other temporary data to the next request.
*
* <code>
* // Create a redirect and flash a messages to the session
* return Redirect::to_profile()->with('message', 'Welcome Back!');
* </code>
*
* @param string $key
* @param mixed $value
* @return Response
......@@ -83,6 +88,17 @@ class Redirect extends Response {
/**
* Magic Method to handle creation of redirects to named routes.
*
* <code>
* // Create a redirect to the "profile" route
* return Redirect::to_profile();
*
* // Create a redirect to the "profile" route with wildcard segments
* return Redirect::to_profile(array($username));
*
* // Create a redirect to the "profile" route using HTTPS
* return Redirect::to_secure_profile();
* </code>
*/
public function __call($method, $parameters)
{
......
......@@ -32,6 +32,14 @@ class Response_Factory {
/**
* Create a new response instance.
*
* <code>
* // Create a response instance
* return Response::make('Hello World');
*
* // Create a response instance with a given status code
* return Response::make('Hello World', 200);
* </code>
*
* @param mixed $content
* @param int $status
* @param array $headers
......@@ -45,6 +53,14 @@ class Response_Factory {
/**
* Create a new response instance containing a view.
*
* <code>
* // Create a new response instance with view content
* return Response::view('home.index');
*
* // Create a new response instance with a view and bound data
* return Response::view('home.index', array('name' => 'Fred'));
* </code>
*
* @param string $view
* @param array $data
* @return Response
......@@ -54,6 +70,26 @@ class Response_Factory {
return new Response($this->view->make($view, $data));
}
/**
* Create a new response instance containing a named view.
*
* <code>
* // Create a new response instance with a named view
* return Response::with('layout');
*
* // Create a new response instance with a named view and bound data
* return Response::with('layout', array('name' => 'Fred'));
* </code>
*
* @param string $name
* @param array $data
* @return Response
*/
public function with($name, $data = array())
{
return new Response($this->view->of($name, $data));
}
/**
* Create a new error response instance.
*
......@@ -61,6 +97,11 @@ class Response_Factory {
*
* Note: The specified error code should correspond to a view in your views/error directory.
*
* <code>
* // Create an error response for status 500
* return Response::error('500');
* </code>
*
* @param int $code
* @param array $data
* @return Response
......@@ -96,6 +137,25 @@ class Response_Factory {
return new Response($this->file->get($path), 200, $headers);
}
/**
* Magic Method for handling the dynamic creation of Responses containing named views.
*
* <code>
* // Create a Response instance with the "layout" named view
* $response = Response::with_layout();
*
* // Create a Response instance with the "layout" named view and bound data
* $response = Response::with_layout(array('name' => 'Fred'));
* </code>
*/
public function __call($method, $parameters)
{
if (strpos($method, 'with_') === 0)
{
return $this->with(substr($method, 5), Arr::get($parameters, 0, array()));
}
}
}
class Response {
......
......@@ -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;
}
}
}
\ No newline at end of file
<?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';
}
}
\ No newline at end of file
<?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;
}
}
}
\ No newline at end of file
<?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.
*/
......
......@@ -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 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))
......
......@@ -32,9 +32,6 @@ class APC extends Driver {
/**
* Load a session by ID.
*
* The session will be retrieved from persistant storage and returned as an array.
* The array contains the session ID, last activity UNIX timestamp, and session data.
*
* @param string $id
* @return array
*/
......
......@@ -43,9 +43,6 @@ class Cookie extends Driver {
/**
* Load a session by ID.
*
* The session will be retrieved from persistant storage and returned as an array.
* The array contains the session ID, last activity UNIX timestamp, and session data.
*
* @param string $id
* @return array
*/
......
......@@ -9,14 +9,14 @@ class Database extends Driver implements Sweeper {
*
* @var Connection
*/
private $connection;
protected $connection;
/**
* The database table to which the sessions should be written.
*
* @var string
*/
private $table;
protected $table;
/**
* Create a new database session driver.
......@@ -34,9 +34,6 @@ class Database extends Driver implements Sweeper {
/**
* Load a session by ID.
*
* The session will be retrieved from persistant storage and returned as an array.
* The array contains the session ID, last activity UNIX timestamp, and session data.
*
* @param string $id
* @return array
*/
......@@ -96,7 +93,7 @@ class Database extends Driver implements Sweeper {
*
* @return Query
*/
private function table()
protected function table()
{
return $this->connection->table($this->table);
}
......
......@@ -7,7 +7,7 @@ use Laravel\Cookie;
abstract class Driver {
/**
* The session payload, which contains the session ID, data and last activity timestamp.
* The session payload, containing the session ID, data and last activity timestamp.
*
* @var array
*/
......@@ -51,9 +51,6 @@ abstract class Driver {
/**
* Load a session by ID.
*
* The session will be retrieved from persistant storage and returned as an array.
* The array contains the session ID, last activity UNIX timestamp, and session data.
*
* @param string $id
* @return array
*/
......@@ -87,8 +84,15 @@ abstract class Driver {
/**
* Get an item from the session.
*
* A default value may also be specified, and will be returned in the requested
* item does not exist in the session.
* A default value may also be specified, and will be returned in the item doesn't exist.
*
* <code>
* // Get an item from the session
* $name = Session::get('name');
*
* // Get an item from the session and return a default value if it doesn't exist
* $name = Session::get('name', 'Fred');
* </code>
*
* @param string $key
* @param mixed $default
......@@ -107,6 +111,11 @@ abstract class Driver {
/**
* Write an item to the session.
*
* <code>
* // Store an item in the session
* Session::put('name', 'Fred');
* </code>
*
* @param string $key
* @param mixed $value
* @return Driver
......@@ -124,6 +133,11 @@ abstract class Driver {
* Flash data only exists for the next request. After that, it will be removed from
* the session. Flash data is useful for temporary status or welcome messages.
*
* <code>
* // Store an item in the session flash data
* Session::flash('name', 'Fred');
* </code>
*
* @param string $key
* @param mixed $value
* @return Driver
......@@ -239,6 +253,14 @@ abstract class Driver {
/**
* Magic Method for retrieving items from the session.
*
* This method is particularly helpful in controllers where access to the IoC container
* is provided through the controller's magic __get method.
*
* <code>
* // Retrieve an item from the session from a controller method
* $name = $this->session->name;
* </code>
*/
public function __get($key)
{
......@@ -247,6 +269,14 @@ abstract class Driver {
/**
* Magic Method for writings items to the session.
*
* This method is particularly helpful in controllers where access to the IoC container
* is provided through the controller's magic __get method.
*
* <code>
* // Set an item in the session from a controller method
* $this->session->name = 'Fred';
* </code>
*/
public function __set($key, $value)
{
......
......@@ -32,9 +32,6 @@ class File extends Driver implements Sweeper {
/**
* Load a session by ID.
*
* The session will be retrieved from persistant storage and returned as an array.
* The array contains the session ID, last activity UNIX timestamp, and session data.
*
* @param string $id
* @return array
*/
......@@ -73,7 +70,10 @@ class File extends Driver implements Sweeper {
{
foreach (glob($this->path.'*') as $file)
{
if ($this->file->type($file) == 'file' and $this->file->modified($file) < $expiration) $this->file->delete($file);
if ($this->file->type($file) == 'file' and $this->file->modified($file) < $expiration)
{
$this->file->delete($file);
}
}
}
......
......@@ -31,9 +31,6 @@ class Memcached extends Driver {
/**
* Load a session by ID.
*
* The session will be retrieved from persistant storage and returned as an array.
* The array contains the session ID, last activity UNIX timestamp, and session data.
*
* @param string $id
* @return array
*/
......
......@@ -3,7 +3,7 @@
class Messages {
/**
* All of the messages.
* All of the registered messages.
*
* @var array
*/
......@@ -12,7 +12,7 @@ class Messages {
/**
* Create a new Messages instance.
*
* The Messages class provides a convenient wrapper around an array of generic messages.
* The Messages class provides a convenient wrapper around an array of strings.
*
* @return void
*/
......@@ -26,6 +26,11 @@ class Messages {
*
* Duplicate messages will not be added.
*
* <code>
* // Add a message to the message collector
* $messages->add('email', 'The e-mail address is invalid.');
* </code>
*
* @param string $key
* @param string $message
* @return void
......@@ -54,6 +59,14 @@ class Messages {
*
* Optionally, a format may be specified for the returned message.
*
* <code>
* // Get the first message for the e-mail attribute
* echo $messages->first('email');
*
* // Get the first message for the e-mail attribute using a format
* echo $messages->first('email', '<p>:message</p>');
* </code>
*
* @param string $key
* @param string $format
* @return string
......@@ -66,6 +79,16 @@ class Messages {
/**
* Get all of the messages for a key.
*
* Optionally, a format may be specified for the returned messages.
*
* <code>
* // Get all of the messages for the e-mail attribute
* $messages = $messages->get('email');
*
* // Get all of the messages for the e-mail attribute using a format
* $messages = $messages->get('email', '<p>:message</p>');
* </code>
*
* @param string $key
* @param string $format
* @return array
......@@ -80,6 +103,11 @@ class Messages {
/**
* Get all of the messages for every key.
*
* <code>
* // Get all of the error messages using a format
* $messages = $messages->all('<p>:message</p>');
* </code>
*
* @param string $format
* @return array
*/
......@@ -102,7 +130,7 @@ class Messages {
* @param string $format
* @return array
*/
private function format($messages, $format)
protected function format($messages, $format)
{
foreach ($messages as $key => &$message)
{
......
<?php namespace Laravel\Validation;
use Closure;
use Laravel\IoC;
use Laravel\Str;
use Laravel\Lang_Factory;
......@@ -13,6 +14,13 @@ class Validator_Factory {
*/
protected $lang;
/**
* The registered custom validators.
*
* @var array
*/
protected $validators = array();
/**
* Create a new validator factory instance.
*
......@@ -34,7 +42,22 @@ class Validator_Factory {
*/
public function make($attributes, $rules, $messages = array())
{
return new Validator($this->lang, $attributes, $rules, $messages);
return new Validator($this->lang, $this->validators, $attributes, $rules, $messages);
}
/**
* Register a custom validation callback.
*
* @param string $name
* @param string $message
* @param Closure $closure
* @return Validator
*/
public function register($name, $message, Closure $closure)
{
$this->validators[$name] = compact('message', 'closure');
return $this;
}
}
......@@ -42,39 +65,46 @@ class Validator_Factory {
class Validator {
/**
* The array being validated.
* The registered custom validators.
*
* @var array
*/
public $attributes;
protected $validators = array();
/**
* The validation rules.
*
* @var array
*/
public $rules;
protected $rules = array();
/**
* The validation messages.
*
* @var array
*/
public $messages;
protected $messages = array();
/**
* The post-validation error messages.
* The language that should be used when retrieving error messages.
*
* @var Messages
* @var string
*/
public $errors;
protected $language;
/**
* The language that should be used when retrieving error messages.
* The size related validation rules.
*
* @var string
* @var array
*/
public $language;
protected $size_rules = array('size', 'between', 'min', 'max');
/**
* The numeric related validation rules.
*
* @var array
*/
protected $numeric_rules = array('numeric', 'integer');
/**
* The database connection that should be used by the validator.
......@@ -84,47 +114,50 @@ class Validator {
public $connection;
/**
* The size related validation rules.
* The array being validated.
*
* @var array
*/
protected $size_rules = array('size', 'between', 'min', 'max');
public $attributes;
/**
* The numeric related validation rules.
* The post-validation error messages.
*
* @var array
* @var Messages
*/
protected $numeric_rules = array('numeric', 'integer');
public $errors;
/**
* Create a new validator instance.
*
* @param Lang_Factory $lang
* @param array $validators
* @param array $attributes
* @param array $rules
* @param array $messages
* @return void
*/
public function __construct(Lang_Factory $lang, $attributes, $rules, $messages = array())
public function __construct(Lang_Factory $lang, $validators, $attributes, $rules, $messages = array())
{
$this->lang = $lang;
$this->rules = $rules;
$this->messages = $messages;
$this->attributes = $attributes;
foreach ($rules as $key => &$rule)
{
$rule = (is_string($rule)) ? explode('|', $rule) : $rule;
}
/**
* Create a new validator instance.
*
* @param array $attributes
* @param array $rules
* @param array $messages
* @return Validator
*/
public static function make($attributes, $rules, $messages = array())
// Register all of the custom validators and their corresponding error messages.
// The validators are executed via the magic __call method. The validator names
// are prefixed with "validate_" to match the built-in validators.
foreach ($validators as $key => $value)
{
return IoC::container()->resolve('laravel.validator')->make($attributes, $rules, $messages);
$this->messages[$key] = $value['message'];
$this->validators['validate_'.$key] = $value['closure'];
}
$this->lang = $lang;
$this->rules = $rules;
$this->attributes = $attributes;
$this->messages = array_merge($this->messages, $messages);
}
/**
......@@ -168,18 +201,18 @@ class Validator {
{
list($rule, $parameters) = $this->parse($rule);
if ( ! method_exists($this, $validator = 'validate_'.$rule))
if ( ! method_exists($this, $validator = 'validate_'.$rule) and ! isset($this->validators[$validator]))
{
throw new \Exception("Validation rule [$rule] doesn't exist.");
}
// No validation will be run for attributes that do not exist unless the rule being validated
// is "required" or "accepted". No other rules have implicit "required" checks.
if ( ! static::validate_required($attribute) and ! in_array($rule, array('required', 'accepted'))) return;
if ( ! $this->validate_required($attribute) and ! in_array($rule, array('required', 'accepted'))) return;
if ( ! $this->$validator($attribute, $parameters))
if ( ! $this->$validator($attribute, $parameters, $this))
{
$message = $this->format_message($this->get_message($attribute, $rule));
$message = $this->format_message($this->get_message($attribute, $rule), $attribute, $rule, $parameters);
$this->errors->add($attribute, $message, $attribute, $rule, $parameters);
}
......@@ -227,7 +260,7 @@ class Validator {
{
$value = $this->attributes[$attribute];
return static::validate_required($attribute) and ($value == 'yes' or $value == '1');
return $this->validate_required($attribute) and ($value == 'yes' or $value == '1');
}
/**
......@@ -403,7 +436,7 @@ class Validator {
*/
protected function validate_image($attribute)
{
return static::validate_mimes($attribute, array('jpg', 'png', 'gif', 'bmp'));
return $this->validate_mimes($attribute, array('jpg', 'png', 'gif', 'bmp'));
}
/**
......@@ -486,10 +519,10 @@ class Validator {
$message = $this->lang->line('validation.'.$rule)->get($this->language);
// For "size" rules that are validating strings or files, we need to adjust
// the default error message for the appropriate type.
// the default error message for the appropriate units.
if (in_array($rule, $this->size_rules) and ! $this->has_rule($attribute, $this->numeric_rules))
{
return (array_key_exists($attribute, $_FILES))
return (array_key_exists($attribute, IoC::container()->resolve('laravel.input')->files()))
? rtrim($message, '.').' '.$this->lang->line('validation.kilobytes')->get($this->language).'.'
: rtrim($message, '.').' '.$this->lang->line('validation.characters')->get($this->language).'.';
}
......@@ -583,4 +616,12 @@ class Validator {
return $this;
}
/**
* Magic Method for calling custom registered validators.
*/
public function __call($method, $parameters)
{
return call_user_func_array($this->validators[$method], $parameters);
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment