From fb811af5fc1b5145edefffa736a226891a886f45 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Fri, 9 Sep 2011 20:55:24 -0500 Subject: [PATCH] more refactoring for dependency injection. --- laravel/benchmark.php | 10 --- laravel/cache/apc.php | 61 +++----------- laravel/cache/driver.php | 21 +++++ laravel/config/container.php | 22 ++--- laravel/container.php | 13 +++ laravel/controller.php | 13 +++ laravel/cookie.php | 12 +++ laravel/facades.php | 12 +++ laravel/file.php | 5 ++ laravel/html.php | 6 +- laravel/input.php | 10 ++- laravel/lang.php | 9 ++ laravel/laravel.php | 2 +- laravel/loader.php | 5 +- laravel/proxy.php | 21 +++++ laravel/redirect.php | 16 ++++ laravel/response.php | 60 ++++++++++++++ laravel/routing/caller.php | 138 ++++++++++++++++++++++++++++--- laravel/routing/delegator.php | 117 -------------------------- laravel/routing/filterer.php | 46 ----------- laravel/routing/route.php | 77 +++++++---------- laravel/routing/router.php | 44 +++++----- laravel/session/apc.php | 3 - laravel/session/cookie.php | 3 - laravel/session/database.php | 9 +- laravel/session/driver.php | 42 ++++++++-- laravel/session/file.php | 8 +- laravel/session/memcached.php | 3 - laravel/validation/messages.php | 34 +++++++- laravel/validation/validator.php | 127 ++++++++++++++++++---------- 30 files changed, 545 insertions(+), 404 deletions(-) create mode 100644 laravel/proxy.php delete mode 100644 laravel/routing/delegator.php delete mode 100644 laravel/routing/filterer.php diff --git a/laravel/benchmark.php b/laravel/benchmark.php index c53403ec..78bec360 100644 --- a/laravel/benchmark.php +++ b/laravel/benchmark.php @@ -14,11 +14,6 @@ class Benchmark { * * The elapsed time since setting a benchmark may checked via the "check" method. * - * - * // Set a benchmark starting time - * Benchmark::start('database'); - * - * * @param string $name * @return void */ @@ -30,11 +25,6 @@ public static function start($name) /** * Get the elapsed time in milliseconds since starting a benchmark. * - * - * // Get the elapsed time since starting a benchmark - * $time = Benchmark::check('database'); - * - * * @param string $name * @return float */ diff --git a/laravel/cache/apc.php b/laravel/cache/apc.php index eba53725..154bde11 100644 --- a/laravel/cache/apc.php +++ b/laravel/cache/apc.php @@ -1,55 +1,13 @@ apc = $apc; $this->key = $key; + $this->proxy = $proxy; } /** @@ -91,7 +50,7 @@ public function has($key) */ 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 @@ protected function retrieve($key) */ 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 @@ public function put($key, $value, $minutes) */ public function forget($key) { - $this->apc->forget($this->key.$key); + $this->proxy->apc_delete($this->key.$key); } } \ No newline at end of file diff --git a/laravel/cache/driver.php b/laravel/cache/driver.php index 756c38ae..658629ec 100644 --- a/laravel/cache/driver.php +++ b/laravel/cache/driver.php @@ -18,6 +18,14 @@ abstract public function has($key); * A default value may also be specified, and will be returned in the requested * item does not exist in the cache. * + * + * // 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'); + * + * * @param string $key * @param mixed $default * @param string $driver @@ -41,6 +49,11 @@ abstract protected function retrieve($key); /** * Write an item to the cache for a given number of minutes. * + * + * // Store an item in the cache for 5 minutes + * Cache::put('name', 'Fred', 5); + * + * * @param string $key * @param mixed $value * @param int $minutes @@ -52,6 +65,14 @@ abstract public function put($key, $value, $minutes); * 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. * + * + * // 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); + * + * * @param string $key * @param mixed $default * @param int $minutes diff --git a/laravel/config/container.php b/laravel/config/container.php index 71d5ce09..b2af55ff 100644 --- a/laravel/config/container.php +++ b/laravel/config/container.php @@ -160,25 +160,13 @@ '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 @@ }), - '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 @@ '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')); }), diff --git a/laravel/container.php b/laravel/container.php index 5c9e546f..ff0f4eac 100644 --- a/laravel/container.php +++ b/laravel/container.php @@ -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. * + * + * // Get the active container instance and call the resolve method + * $instance = IoC::container()->resolve('instance'); + * + * * @return Container */ public static function container() @@ -24,6 +29,14 @@ public static function container() /** * Magic Method for calling methods on the active container instance. + * + * + * // Call the "resolve" method on the active container instance + * $instance = IoC::resolve('instance'); + * + * // Equivalent operation using the "container" method + * $instance = IoC::container()->resolve('instance'); + * */ public static function __callStatic($method, $parameters) { diff --git a/laravel/controller.php b/laravel/controller.php index 08f7a2cb..2b1ee887 100644 --- a/laravel/controller.php +++ b/laravel/controller.php @@ -26,6 +26,19 @@ public function __call($method, $parameters) /** * 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. + * + * + * // Resolve the "laravel.input" instance from the IoC container + * $input = $this->input; + * + * // Resolve the "mailer" instance from the IoC container + * $mongo = $this->mailer; + * + * */ public function __get($key) { diff --git a/laravel/cookie.php b/laravel/cookie.php index 4eaea702..8765113e 100644 --- a/laravel/cookie.php +++ b/laravel/cookie.php @@ -72,6 +72,18 @@ public function forever($name, $value, $path = '/', $domain = null, $secure = fa * * 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. + * + * + * // 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); + * + * * @param string $name * @param string $value * @param int $minutes diff --git a/laravel/facades.php b/laravel/facades.php index 06812c42..80901b11 100644 --- a/laravel/facades.php +++ b/laravel/facades.php @@ -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 { /** diff --git a/laravel/file.php b/laravel/file.php index fe3378be..06afeef7 100644 --- a/laravel/file.php +++ b/laravel/file.php @@ -1,5 +1,10 @@ entities($alt); + $attributes['alt'] = $alt; return 'attributes($attributes).'>'; } diff --git a/laravel/input.php b/laravel/input.php index 0fc8c10d..62183777 100644 --- a/laravel/input.php +++ b/laravel/input.php @@ -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 @@ public function upload($key, $path) /** * 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. + * + * + * // Retrieve the "name" input item from a controller method + * $name = $this->input->name; + * */ public function __get($key) { diff --git a/laravel/lang.php b/laravel/lang.php index ee4a39f2..38897605 100644 --- a/laravel/lang.php +++ b/laravel/lang.php @@ -200,6 +200,15 @@ protected function load($file) /** * 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. + * + * + * // Display a language line by casting it to a string + * echo Lang::line('messages.welcome'); + * + * */ public function __toString() { diff --git a/laravel/laravel.php b/laravel/laravel.php index 100a8cc0..45f87517 100644 --- a/laravel/laravel.php +++ b/laravel/laravel.php @@ -57,7 +57,7 @@ // -------------------------------------------------------------- // 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)) { diff --git a/laravel/loader.php b/laravel/loader.php index bc6296fb..b6586d45 100644 --- a/laravel/loader.php +++ b/laravel/loader.php @@ -39,10 +39,7 @@ public function load($class) { $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) { diff --git a/laravel/proxy.php b/laravel/proxy.php new file mode 100644 index 00000000..c81e9390 --- /dev/null +++ b/laravel/proxy.php @@ -0,0 +1,21 @@ + + * // Create a redirect and flash a messages to the session + * return Redirect::to_profile()->with('message', 'Welcome Back!'); + * + * * @param string $key * @param mixed $value * @return Response @@ -83,6 +88,17 @@ public function with($key, $value) /** * Magic Method to handle creation of redirects to named routes. + * + * + * // 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(); + * */ public function __call($method, $parameters) { diff --git a/laravel/response.php b/laravel/response.php index 3bc877be..8300cbe0 100644 --- a/laravel/response.php +++ b/laravel/response.php @@ -32,6 +32,14 @@ public function __construct(View_Factory $view, File $file) /** * Create a new response instance. * + * + * // Create a response instance + * return Response::make('Hello World'); + * + * // Create a response instance with a given status code + * return Response::make('Hello World', 200); + * + * * @param mixed $content * @param int $status * @param array $headers @@ -45,6 +53,14 @@ public function make($content, $status = 200, $headers = array()) /** * Create a new response instance containing a view. * + * + * // 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')); + * + * * @param string $view * @param array $data * @return Response @@ -54,6 +70,26 @@ public function view($view, $data = array()) return new Response($this->view->make($view, $data)); } + /** + * Create a new response instance containing a named view. + * + * + * // 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')); + * + * + * @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 @@ public function view($view, $data = array()) * * Note: The specified error code should correspond to a view in your views/error directory. * + * + * // Create an error response for status 500 + * return Response::error('500'); + * + * * @param int $code * @param array $data * @return Response @@ -96,6 +137,25 @@ public function download($path, $name = null, $headers = array()) return new Response($this->file->get($path), 200, $headers); } + /** + * Magic Method for handling the dynamic creation of Responses containing named views. + * + * + * // 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')); + * + */ + public function __call($method, $parameters) + { + if (strpos($method, 'with_') === 0) + { + return $this->with(substr($method, 5), Arr::get($parameters, 0, array())); + } + } + } class Response { diff --git a/laravel/routing/caller.php b/laravel/routing/caller.php index 5218e023..088ba45b 100644 --- a/laravel/routing/caller.php +++ b/laravel/routing/caller.php @@ -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 @@ public function call(Route $route) 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 @@ public function call(Route $route) 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 @@ protected function before(Route $route) { $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 @@ protected function finish(Route $route, $response) { 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 diff --git a/laravel/routing/delegator.php b/laravel/routing/delegator.php deleted file mode 100644 index 1bbe3b03..00000000 --- a/laravel/routing/delegator.php +++ /dev/null @@ -1,117 +0,0 @@ -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 diff --git a/laravel/routing/filterer.php b/laravel/routing/filterer.php deleted file mode 100644 index 9d00a3fe..00000000 --- a/laravel/routing/filterer.php +++ /dev/null @@ -1,46 +0,0 @@ -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 diff --git a/laravel/routing/route.php b/laravel/routing/route.php index e14e4d57..16f8aa9f 100644 --- a/laravel/routing/route.php +++ b/laravel/routing/route.php @@ -1,7 +1,6 @@ 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 @@ public function __construct($key, $callback, $parameters = array()) */ 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 @@ public function call() * * @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 @@ public function filters($name) } /** - * 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 @@ public function handles($uri) 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. */ diff --git a/laravel/routing/router.php b/laravel/routing/router.php index e66bbc5e..c580e17b 100644 --- a/laravel/routing/router.php +++ b/laravel/routing/router.php @@ -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 @@ public function find($name) } /** - * 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 @@ public function route() { 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 @@ public function route() * * 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 @@ protected function route_to_controller() // 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 @@ protected function route_to_controller() * * 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)) diff --git a/laravel/session/apc.php b/laravel/session/apc.php index db996e28..055551f6 100644 --- a/laravel/session/apc.php +++ b/laravel/session/apc.php @@ -32,9 +32,6 @@ public function __construct(\Laravel\Cache\APC $apc, $lifetime) /** * 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 */ diff --git a/laravel/session/cookie.php b/laravel/session/cookie.php index dc7cc17a..203f054a 100644 --- a/laravel/session/cookie.php +++ b/laravel/session/cookie.php @@ -43,9 +43,6 @@ public function __construct(Crypter $crypter, \Laravel\Cookie $cookie, $config) /** * 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 */ diff --git a/laravel/session/database.php b/laravel/session/database.php index 49756a42..9e17268d 100644 --- a/laravel/session/database.php +++ b/laravel/session/database.php @@ -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 @@ public function __construct(Connection $connection, $table) /** * 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 @@ public function sweep($expiration) * * @return Query */ - private function table() + protected function table() { return $this->connection->table($this->table); } diff --git a/laravel/session/driver.php b/laravel/session/driver.php index 67077119..d3a4c2d1 100644 --- a/laravel/session/driver.php +++ b/laravel/session/driver.php @@ -7,7 +7,7 @@ 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 @@ public function start($id, $config) /** * 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 @@ public function has($key) /** * 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. + * + * + * // 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'); + * * * @param string $key * @param mixed $default @@ -107,6 +111,11 @@ public function get($key, $default = null) /** * Write an item to the session. * + * + * // Store an item in the session + * Session::put('name', 'Fred'); + * + * * @param string $key * @param mixed $value * @return Driver @@ -124,6 +133,11 @@ public function put($key, $value) * 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. * + * + * // Store an item in the session flash data + * Session::flash('name', 'Fred'); + * + * * @param string $key * @param mixed $value * @return Driver @@ -239,6 +253,14 @@ protected function write_cookie(Cookie $cookies, $config) /** * 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. + * + * + * // Retrieve an item from the session from a controller method + * $name = $this->session->name; + * */ public function __get($key) { @@ -247,6 +269,14 @@ public function __get($key) /** * 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. + * + * + * // Set an item in the session from a controller method + * $this->session->name = 'Fred'; + * */ public function __set($key, $value) { diff --git a/laravel/session/file.php b/laravel/session/file.php index b9cd2723..9088585a 100644 --- a/laravel/session/file.php +++ b/laravel/session/file.php @@ -32,9 +32,6 @@ public function __construct(\Laravel\File $file, $path) /** * 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 @@ public function sweep($expiration) { 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); + } } } diff --git a/laravel/session/memcached.php b/laravel/session/memcached.php index 9771eb57..aff59149 100644 --- a/laravel/session/memcached.php +++ b/laravel/session/memcached.php @@ -31,9 +31,6 @@ public function __construct(\Laravel\Cache\Memcached $memcached, $lifetime) /** * 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 */ diff --git a/laravel/validation/messages.php b/laravel/validation/messages.php index 08f460ca..26985cc8 100644 --- a/laravel/validation/messages.php +++ b/laravel/validation/messages.php @@ -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 @@ public function __construct($messages = array()) * * Duplicate messages will not be added. * + * + * // Add a message to the message collector + * $messages->add('email', 'The e-mail address is invalid.'); + * + * * @param string $key * @param string $message * @return void @@ -54,6 +59,14 @@ public function has($key) * * Optionally, a format may be specified for the returned message. * + * + * // 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', '

:message

'); + *
+ * * @param string $key * @param string $format * @return string @@ -66,6 +79,16 @@ public function first($key, $format = ':message') /** * Get all of the messages for a key. * + * Optionally, a format may be specified for the returned messages. + * + * + * // 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', '

:message

'); + *
+ * * @param string $key * @param string $format * @return array @@ -80,6 +103,11 @@ public function get($key = null, $format = ':message') /** * Get all of the messages for every key. * + * + * // Get all of the error messages using a format + * $messages = $messages->all('

:message

'); + *
+ * * @param string $format * @return array */ @@ -102,7 +130,7 @@ public function all($format = ':message') * @param string $format * @return array */ - private function format($messages, $format) + protected function format($messages, $format) { foreach ($messages as $key => &$message) { diff --git a/laravel/validation/validator.php b/laravel/validation/validator.php index f847ab9a..2b21f335 100644 --- a/laravel/validation/validator.php +++ b/laravel/validation/validator.php @@ -1,5 +1,6 @@ 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,46 +65,32 @@ public function make($attributes, $rules, $messages = array()) 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; - - /** - * The post-validation error messages. - * - * @var Messages - */ - public $errors; + protected $messages = array(); /** * The language that should be used when retrieving error messages. * * @var string */ - public $language; - - /** - * The database connection that should be used by the validator. - * - * @var DB\Connection - */ - public $connection; + protected $language; /** * The size related validation rules. @@ -97,34 +106,58 @@ class Validator { */ protected $numeric_rules = array('numeric', 'integer'); + /** + * The database connection that should be used by the validator. + * + * @var DB\Connection + */ + public $connection; + + /** + * The array being validated. + * + * @var array + */ + public $attributes; + + /** + * The post-validation error messages. + * + * @var Messages + */ + 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()) { + foreach ($rules as $key => &$rule) + { + $rule = (is_string($rule)) ? explode('|', $rule) : $rule; + } + + // 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) + { + $this->messages[$key] = $value['message']; + + $this->validators['validate_'.$key] = $value['closure']; + } + $this->lang = $lang; $this->rules = $rules; - $this->messages = $messages; $this->attributes = $attributes; - } - - /** - * Create a new validator instance. - * - * @param array $attributes - * @param array $rules - * @param array $messages - * @return Validator - */ - public static function make($attributes, $rules, $messages = array()) - { - return IoC::container()->resolve('laravel.validator')->make($attributes, $rules, $messages); + $this->messages = array_merge($this->messages, $messages); } /** @@ -168,18 +201,18 @@ protected function check($attribute, $rule) { 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 @@ protected function validate_accepted($attribute) { $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 @@ protected function validate_active_url($attribute) */ 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 @@ protected function get_message($attribute, $rule) $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 @@ public function connection(Database\Connection $connection) 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