Commit f0f3dffc authored by Taylor Otwell's avatar Taylor Otwell

added module support!

parent 927c522e
local/*
\ No newline at end of file
...@@ -63,6 +63,42 @@ return array( ...@@ -63,6 +63,42 @@ return array(
'timezone' => 'UTC', 'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Auto-Loaded Packages
|--------------------------------------------------------------------------
|
| The packages that should be auto-loaded each time Laravel handles
| a request. These should generally be packages that you use on almost
| every request to your application.
|
| Each package specified here will be bootstrapped and can be conveniently
| used by your application's routes, models, and libraries.
|
| Note: The package names in this array should correspond to a package
| directory in application/packages.
|
*/
'packages' => array(),
/*
|--------------------------------------------------------------------------
| Active Modules
|--------------------------------------------------------------------------
|
| Modules are a convenient way to organize your application into logical
| components. Each module may have its own libraries, models, routes,
| views, language files, and configuration.
|
| Here you may specify which modules are "active" for your application.
| This simply gives Laravel an easy way to know which directories to
| check when auto-loading your classes, routes, and views.
|
*/
'modules' => array(),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Application Key | Application Key
......
...@@ -50,7 +50,7 @@ return array( ...@@ -50,7 +50,7 @@ return array(
| |
*/ */
'logger' => function($severity, $message) 'logger' => function($severity, $message, $trace)
{ {
File::append(STORAGE_PATH.'log.txt', date('Y-m-d H:i:s').' '.$severity.' - '.$message.PHP_EOL); File::append(STORAGE_PATH.'log.txt', date('Y-m-d H:i:s').' '.$severity.' - '.$message.PHP_EOL);
}, },
......
<?php
return array(
'url' => 'http://localhost/laravel/public'
);
\ No newline at end of file
<?php
return array(
/*
|--------------------------------------------------------------------------
| Auto-Loaded Packages
|--------------------------------------------------------------------------
|
| The packages that should be auto-loaded each time Laravel handles
| a request. These should generally be packages that you use on almost
| every request to your application.
|
| Each package specified here will be bootstrapped and can be conveniently
| used by your application's routes, models, and libraries.
|
| Note: The package names in this array should correspond to a package
| directory in application/packages.
|
*/
'autoload' => array(),
);
\ No newline at end of file
<?php
return array(
/*
|--------------------------------------------------------------------------
| Named Views
|--------------------------------------------------------------------------
|
| All of the named views for your application. Once you have defined the
| named view, you can create a View instance for that view using the
| View::of dynamic method.
|
| For example, if you define a "layout" named view, you could create an
| instance of that View by calling: View::of_layout().
|
| For more info, check out: http://laravel.com/docs/start/views#named
|
*/
'names' => array(
'home' => 'home/index',
),
);
\ No newline at end of file
...@@ -46,13 +46,13 @@ return array( ...@@ -46,13 +46,13 @@ return array(
'before' => function() 'before' => function()
{ {
// Do stuff before every request is executed. // Do stuff before every request to your application.
}, },
'after' => function($response) 'after' => function($response)
{ {
// Do stuff after every request is executed. // Do stuff after every request to your application.
}, },
......
<?php
namespace Entities;
class User extends \Eloquent {
public function friends()
{
return $this->has_many('Entities\\Friend');
}
public function roles()
{
return $this->has_and_belongs_to_many('Role');
}
}
class Friend extends \Eloquent {}
\ No newline at end of file
<?php
class Role extends \Eloquent {}
\ No newline at end of file
...@@ -41,7 +41,7 @@ return array( ...@@ -41,7 +41,7 @@ return array(
'GET /' => function() 'GET /' => function()
{ {
return View::make('home/index'); return View::make('home.index');
}, },
); );
\ No newline at end of file
*.sqlite
\ No newline at end of file
...@@ -12,8 +12,7 @@ return array( ...@@ -12,8 +12,7 @@ return array(
| footer partial each time the view is created. | footer partial each time the view is created.
| |
| The composer will receive an instance of the view being created, and is | The composer will receive an instance of the view being created, and is
| free to modify the view however you wish. Be sure to always return the | free to modify the view however you wish.
| view instance at the end of your composer.
| |
| For more information, check out: http://laravel.com/docs/start/views#composers | For more information, check out: http://laravel.com/docs/start/views#composers
| |
...@@ -21,7 +20,7 @@ return array( ...@@ -21,7 +20,7 @@ return array(
'home/index' => function($view) 'home/index' => function($view)
{ {
return $view; // Do anything you want to the view.
}, },
); );
\ No newline at end of file
...@@ -84,7 +84,7 @@ ...@@ -84,7 +84,7 @@
</div> </div>
<div class="wrapper footer"> <div class="wrapper footer">
<?php echo System\Benchmark::check('laravel').'ms | '.System\Benchmark::memory(); ?> <?php echo System\Benchmark::check('laravel').'ms | '.System\Benchmark::memory().'mb'; ?>
</div> </div>
</body> </body>
</html> </html>
\ No newline at end of file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
\ No newline at end of file
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
* Laravel - A clean and classy framework for PHP web development. * Laravel - A clean and classy framework for PHP web development.
* *
* @package Laravel * @package Laravel
* @version 1.4.1 * @version 1.5.0
* @author Taylor Otwell * @author Taylor Otwell
* @link http://laravel.com * @link http://laravel.com
*/ */
...@@ -24,30 +24,43 @@ define('APP_PATH', realpath('../application').'/'); ...@@ -24,30 +24,43 @@ define('APP_PATH', realpath('../application').'/');
define('SYS_PATH', realpath($system = '../system').'/'); define('SYS_PATH', realpath($system = '../system').'/');
// -------------------------------------------------------------- // --------------------------------------------------------------
// The path to the directory containing the system directory. // The path to the public directory.
// -------------------------------------------------------------- // --------------------------------------------------------------
define('BASE_PATH', realpath(str_replace('system', '', $system)).'/'); define('PUBLIC_PATH', realpath(__DIR__).'/');
// -------------------------------------------------------------- // --------------------------------------------------------------
// The path to the public directory. // The path to the packages directory.
// -------------------------------------------------------------- // --------------------------------------------------------------
define('PUBLIC_PATH', realpath(__DIR__).'/'); define('PACKAGE_PATH', realpath('../packages').'/');
// --------------------------------------------------------------
// The path to the modules directory.
// --------------------------------------------------------------
define('MODULE_PATH', realpath('../modules').'/');
// --------------------------------------------------------------
// The path to the storage directory.
// --------------------------------------------------------------
define('STORAGE_PATH', realpath('../storage').'/');
// --------------------------------------------------------------
// The path to the directory containing the system directory.
// --------------------------------------------------------------
define('BASE_PATH', realpath(str_replace('system', '', $system)).'/');
// -------------------------------------------------------------- // --------------------------------------------------------------
// Define various other framework paths. // Define various other framework paths.
// -------------------------------------------------------------- // --------------------------------------------------------------
$constants = array( $constants = array(
'CACHE_PATH' => APP_PATH.'storage/cache/', 'CACHE_PATH' => STORAGE_PATH.'cache/',
'CONFIG_PATH' => APP_PATH.'config/', 'CONFIG_PATH' => APP_PATH.'config/',
'DATABASE_PATH' => APP_PATH.'storage/db/', 'DATABASE_PATH' => STORAGE_PATH.'db/',
'LANG_PATH' => APP_PATH.'lang/', 'LANG_PATH' => APP_PATH.'lang/',
'LIBRARY_PATH' => APP_PATH.'libraries/', 'LIBRARY_PATH' => APP_PATH.'libraries/',
'MODEL_PATH' => APP_PATH.'models/', 'MODEL_PATH' => APP_PATH.'models/',
'PACKAGE_PATH' => APP_PATH.'packages/',
'ROUTE_PATH' => APP_PATH.'routes/', 'ROUTE_PATH' => APP_PATH.'routes/',
'SCRIPT_PATH' => PUBLIC_PATH.'js/', 'SCRIPT_PATH' => PUBLIC_PATH.'js/',
'SESSION_PATH' => APP_PATH.'storage/sessions/', 'SESSION_PATH' => STORAGE_PATH.'sessions/',
'STORAGE_PATH' => APP_PATH.'storage/',
'STYLE_PATH' => PUBLIC_PATH.'css/', 'STYLE_PATH' => PUBLIC_PATH.'css/',
'VIEW_PATH' => APP_PATH.'views/', 'VIEW_PATH' => APP_PATH.'views/',
); );
...@@ -70,7 +83,6 @@ define('EXT', '.php'); ...@@ -70,7 +83,6 @@ define('EXT', '.php');
require SYS_PATH.'loader'.EXT; require SYS_PATH.'loader'.EXT;
require SYS_PATH.'config'.EXT; require SYS_PATH.'config'.EXT;
require SYS_PATH.'arr'.EXT; require SYS_PATH.'arr'.EXT;
// -------------------------------------------------------------- // --------------------------------------------------------------
// Register the auto-loader. // Register the auto-loader.
// -------------------------------------------------------------- // --------------------------------------------------------------
...@@ -145,7 +157,7 @@ require SYS_PATH.'routing/filter'.EXT; ...@@ -145,7 +157,7 @@ require SYS_PATH.'routing/filter'.EXT;
// -------------------------------------------------------------- // --------------------------------------------------------------
require SYS_PATH.'package'.EXT; require SYS_PATH.'package'.EXT;
System\Package::load(System\Config::get('package.autoload')); System\Package::load(System\Config::get('application.packages'));
// -------------------------------------------------------------- // --------------------------------------------------------------
// Register the route filters. // Register the route filters.
...@@ -157,12 +169,28 @@ System\Routing\Filter::register(require APP_PATH.'filters'.EXT); ...@@ -157,12 +169,28 @@ System\Routing\Filter::register(require APP_PATH.'filters'.EXT);
// -------------------------------------------------------------- // --------------------------------------------------------------
$response = System\Routing\Filter::call('before', array(), true); $response = System\Routing\Filter::call('before', array(), true);
// ---------------------------------------------------------- // --------------------------------------------------------------
// Execute the route function. // Execute the route function.
// ---------------------------------------------------------- // --------------------------------------------------------------
if (is_null($response)) if (is_null($response))
{ {
$route = System\Routing\Router::make(System\Request::method(), System\Request::uri(), new System\Routing\Loader(APP_PATH))->route(); $segments = explode('/', $uri = Request::uri());
if (in_array($segments[0], System\Config::get('application.modules')))
{
$route_path = MODULE_PATH.$segments[0].'/';
if (file_exists($filters = $route_path.'filters'.EXT))
{
System\Routing\Filter::register(require $filters);
}
}
else
{
$route_path = APP_PATH;
}
$route = System\Routing\Router::make(System\Request::method(), $uri, new System\Routing\Loader($route_path))->route();
$response = (is_null($route)) ? System\Response::error('404') : $route->call(); $response = (is_null($route)) ? System\Response::error('404') : $route->call();
} }
...@@ -171,14 +199,14 @@ else ...@@ -171,14 +199,14 @@ else
$response = System\Response::prepare($response); $response = System\Response::prepare($response);
} }
// ---------------------------------------------------------- // --------------------------------------------------------------
// Execute the global "after" filter. // Execute the global "after" filter.
// ---------------------------------------------------------- // --------------------------------------------------------------
System\Routing\Filter::call('after', array($response)); System\Routing\Filter::call('after', array($response));
// ---------------------------------------------------------- // --------------------------------------------------------------
// Stringify the response. // Stringify the response.
// ---------------------------------------------------------- // --------------------------------------------------------------
$response->content = (string) $response->content; $response->content = (string) $response->content;
// -------------------------------------------------------------- // --------------------------------------------------------------
......
...@@ -6,32 +6,22 @@ Laravel is a clean and classy framework for PHP web development. Freeing you fro ...@@ -6,32 +6,22 @@ Laravel is a clean and classy framework for PHP web development. Freeing you fro
Stay true to the web with RESTful routing: Stay true to the web with RESTful routing:
```php 'GET /' => function()
<?php {
return View::make('home/index');
'GET /' => function() }
{
return View::make('home/index');
}
```
Redirect to a named route and flash something to the session: Redirect to a named route and flash something to the session:
```php return Redirect::to_profile()->with('message', 'Welcome Back!');
<?php return Redirect::to_profile()->with('message', 'Welcome Back!');
```
Retrieve a blog post and eagerly load the comments using Eloquent ORM: Retrieve a blog post and eagerly load the comments using Eloquent ORM:
```php $posts = Post::with('comments')->find(1);
<?php $posts = Post::with('comments')->find(1);
```
Get input from the previous request to re-populate a form: Get input from the previous request to re-populate a form:
```php echo Input::old('email');
<?php echo Input::old('email');
```
### Ready To Learn More? ### Ready To Learn More?
......
...@@ -36,21 +36,19 @@ class Config { ...@@ -36,21 +36,19 @@ class Config {
*/ */
public static function get($key, $default = null) public static function get($key, $default = null)
{ {
if (strpos($key, '.') === false) list($module, $file, $key) = static::parse($key);
{
static::load($key);
return Arr::get(static::$items, $key, $default); if ( ! static::load($module, $file))
{
return is_callable($default) ? call_user_func($default) : $default;
} }
list($file, $key) = static::parse($key); if (is_null($key))
if ( ! static::load($file))
{ {
return is_callable($default) ? call_user_func($default) : $default; return static::$items[$module][$file];
} }
return Arr::get(static::$items[$file], $key, $default); return Arr::get(static::$items[$module][$file], $key, $default);
} }
/** /**
...@@ -62,11 +60,14 @@ class Config { ...@@ -62,11 +60,14 @@ class Config {
*/ */
public static function set($key, $value) public static function set($key, $value)
{ {
list($file, $key) = static::parse($key); list($module, $file, $key) = static::parse($key);
static::load($file); if (is_null($key) or ! static::load($module, $file))
{
throw new \Exception("Unable to find configuration file item [$key].");
}
static::$items[$file][$key] = $value; static::$items[$module][$file][$key] = $value;
} }
/** /**
...@@ -80,14 +81,24 @@ class Config { ...@@ -80,14 +81,24 @@ class Config {
*/ */
private static function parse($key) private static function parse($key)
{ {
$segments = explode('.', $key); // Check for a module qualifier. If a module name is present, we need to extract it from
// the configuration key, otherwise, we will use "application" as the module.
$module = (strpos($key, '::') !== false) ? substr($key, 0, strpos($key, ':')) : 'application';
if (count($segments) < 2) // If the configuration item is stored in a module, we need to strip the module qualifier
// off of the configuration key before continuing.
if ($module != 'application')
{ {
throw new \Exception("Invalid configuration key [$key]."); $key = substr($key, strpos($key, ':') + 2);
} }
return array($segments[0], implode('.', array_slice($segments, 1))); $segments = explode('.', $key);
// If there is more than one segment, we need to splice together and portion of the
// configuration key that comes after the first segment, which is the file name.
$key = (count($segments) > 1) ? implode('.', array_slice($segments, 1)) : null;
return array($module, $segments[0], $key);
} }
/** /**
...@@ -97,25 +108,32 @@ class Config { ...@@ -97,25 +108,32 @@ class Config {
* Any environment specific configuration files will be merged with the root file. * Any environment specific configuration files will be merged with the root file.
* *
* @param string $file * @param string $file
* @param string $module
* @return bool * @return bool
*/ */
public static function load($file) public static function load($module, $file)
{ {
if (array_key_exists($file, static::$items)) return true; // If the configuration items for this module and file have already been
// loaded, we can bail out of this method.
if (isset(static::$items[$module]) and array_key_exists($file, static::$items[$module])) return true;
$path = ($module === 'application') ? CONFIG_PATH : MODULE_PATH.$module.'/config/';
$config = (file_exists($path = CONFIG_PATH.$file.EXT)) ? require $path : array(); // Load the base configuration items for the module and file.
$config = (file_exists($base = $path.$file.EXT)) ? require $base : array();
if (isset($_SERVER['LARAVEL_ENV']) and file_exists($path = CONFIG_PATH.$_SERVER['LARAVEL_ENV'].'/'.$file.EXT)) // Merge any enviornment specific configuration items for the module and file.
if (isset($_SERVER['LARAVEL_ENV']) and file_exists($path = $path.$_SERVER['LARAVEL_ENV'].'/'.$file.EXT))
{ {
$config = array_merge($config, require $path); $config = array_merge($config, require $path);
} }
if (count($config) > 0) if (count($config) > 0)
{ {
static::$items[$file] = $config; static::$items[$module][$file] = $config;
} }
return isset(static::$items[$file]); return isset(static::$items[$module][$file]);
} }
} }
\ No newline at end of file
...@@ -151,7 +151,22 @@ abstract class Model { ...@@ -151,7 +151,22 @@ abstract class Model {
return $class::$table; return $class::$table;
} }
return strtolower(Inflector::plural($class)); return strtolower(Inflector::plural(static::model($class)));
}
/**
* Get an Eloquent model name without any namespaces.
*
* @param string|Model $model
* @return string
*/
public static function model($model)
{
$class = (is_object($model)) ? get_class($model) : $model;
$segments = array_reverse(explode('\\', $class));
return $segments[0];
} }
/** /**
...@@ -254,7 +269,7 @@ abstract class Model { ...@@ -254,7 +269,7 @@ abstract class Model {
*/ */
private function has_one_or_many($model, $foreign_key) private function has_one_or_many($model, $foreign_key)
{ {
$this->relating_key = (is_null($foreign_key)) ? strtolower(get_class($this)).'_id' : $foreign_key; $this->relating_key = (is_null($foreign_key)) ? strtolower(static::model($this)).'_id' : $foreign_key;
return static::query($model)->where($this->relating_key, '=', $this->id); return static::query($model)->where($this->relating_key, '=', $this->id);
} }
...@@ -308,11 +323,11 @@ abstract class Model { ...@@ -308,11 +323,11 @@ abstract class Model {
// Allowing the overriding of the foreign and associated keys provides the flexibility for // Allowing the overriding of the foreign and associated keys provides the flexibility for
// self-referential many-to-many relationships, such as a "buddy list". // self-referential many-to-many relationships, such as a "buddy list".
$this->relating_key = (is_null($foreign_key)) ? strtolower(get_class($this)).'_id' : $foreign_key; $this->relating_key = (is_null($foreign_key)) ? strtolower(static::model($this)).'_id' : $foreign_key;
// The associated key is the foreign key name of the related model. So, if the related model // The associated key is the foreign key name of the related model. So, if the related model
// is "Role", the associated key on the intermediate table would be "role_id". // is "Role", the associated key on the intermediate table would be "role_id".
$associated_key = (is_null($associated_key)) ? strtolower($model).'_id' : $associated_key; $associated_key = (is_null($associated_key)) ? strtolower(static::model($model)).'_id' : $associated_key;
return static::query($model) return static::query($model)
->select(array(static::table($model).'.*')) ->select(array(static::table($model).'.*'))
...@@ -325,13 +340,13 @@ abstract class Model { ...@@ -325,13 +340,13 @@ abstract class Model {
* *
* By default, the intermediate table name is the plural names of the models * By default, the intermediate table name is the plural names of the models
* arranged alphabetically and concatenated with an underscore. * arranged alphabetically and concatenated with an underscore.
* *
* @param string $model * @param string $model
* @return string * @return string
*/ */
private function intermediate_table($model) private function intermediate_table($model)
{ {
$models = array(Inflector::plural($model), Inflector::plural(get_class($this))); $models = array(Inflector::plural(static::model($model)), Inflector::plural(static::model($this)));
sort($models); sort($models);
......
...@@ -68,16 +68,16 @@ class Lang { ...@@ -68,16 +68,16 @@ class Lang {
$language = Config::get('application.language'); $language = Config::get('application.language');
} }
list($file, $line) = $this->parse($this->key); list($module, $file, $line) = $this->parse($this->key, $language);
$this->load($file, $language); $this->load($module, $file, $language);
if ( ! isset(static::$lines[$language.$file][$line])) if ( ! isset(static::$lines[$module][$language.$file][$line]))
{ {
return is_callable($default) ? call_user_func($default) : $default; return is_callable($default) ? call_user_func($default) : $default;
} }
$line = static::$lines[$language.$file][$line]; $line = static::$lines[$module][$language.$file][$line];
foreach ($this->replacements as $key => $value) foreach ($this->replacements as $key => $value)
{ {
...@@ -94,34 +94,51 @@ class Lang { ...@@ -94,34 +94,51 @@ class Lang {
* while the right side of the dot is the item within that file. * while the right side of the dot is the item within that file.
* *
* @param string $key * @param string $key
* @param string $language
* @return array * @return array
*/ */
private function parse($key) private function parse($key, $language)
{ {
// Check for a module qualifier. If a module name is present, we need to extract it from
// the language line, otherwise, we will use "application" as the module.
$module = (strpos($key, '::') !== false) ? substr($key, 0, strpos($key, ':')) : 'application';
// If the language line is stored in a module, we need to strip the module qualifier
// off of the language key before continuing.
if ($module != 'application')
{
$key = substr($key, strpos($key, ':') + 2);
}
$segments = explode('.', $key); $segments = explode('.', $key);
if (count($segments) < 2) if (count($segments) > 1)
{ {
throw new \Exception("Invalid language key [$key]."); return array($module, $segments[0], $segments[1]);
} }
return array($segments[0], implode('.', array_slice($segments, 1))); throw new \Exception("Invalid language line [$key]. A specific line must be specified.");
} }
/** /**
* Load a language file. * Load a language file.
* *
* @param string $module
* @param string $file * @param string $file
* @param string $language * @param string $language
* @return void * @return void
*/ */
private function load($file, $language) private function load($module, $file, $language)
{ {
if (array_key_exists($language.$file, static::$lines)) return; // If the language lines for the given module, file, and language have already been
// loaded, we can bail out of this method.
if (isset(static::$lines[$module][$language.$file])) return;
$path = ($module === 'application') ? LANG_PATH : MODULE_PATH.$module.'/lang/';
if (file_exists($path = LANG_PATH.$language.'/'.$file.EXT)) if (file_exists($path = $path.$language.'/'.$file.EXT))
{ {
static::$lines[$language.$file] = require $path; static::$lines[$module][$language.$file] = require $path;
} }
} }
......
...@@ -16,6 +16,13 @@ class Loader { ...@@ -16,6 +16,13 @@ class Loader {
*/ */
private static $aliases = array(); private static $aliases = array();
/**
* All of the active modules.
*
* @var array
*/
private static $modules = array();
/** /**
* Bootstrap the auto-loader. * Bootstrap the auto-loader.
* *
...@@ -23,16 +30,15 @@ class Loader { ...@@ -23,16 +30,15 @@ class Loader {
*/ */
public static function bootstrap() public static function bootstrap()
{ {
static::$aliases = require CONFIG_PATH.'aliases'.EXT; static::$aliases = Config::get('aliases');
static::$modules = Config::get('application.modules');
} }
/** /**
* Load a class file for a given class name. * Load a class file for a given class name.
* *
* This function is registered on the SPL auto-loader stack by the front controller during each request. * This function is registered on the SPL auto-loader stack by the front controller during each request.
* * All Laravel class names follow a namespace to directory convention.
* All Laravel class names follow a namespace to directory convention. So, if a class exists in
* application/libraries/user, it shouold be placed in the "User" namespace.
* *
* @param string $class * @param string $class
* @return void * @return void
...@@ -46,13 +52,60 @@ class Loader { ...@@ -46,13 +52,60 @@ class Loader {
return class_alias(static::$aliases[$class], $class); return class_alias(static::$aliases[$class], $class);
} }
if ( ! static::load_from_registered($file))
{
static::load_from_module($file);
}
}
/**
* Load a class that is stored in the registered directories.
*
* @param string $file
* @return bool
*/
private static function load_from_registered($file)
{
foreach (static::$paths as $directory) foreach (static::$paths as $directory)
{ {
if (file_exists($path = $directory.$file.EXT)) if (file_exists($path = $directory.$file.EXT))
{ {
require $path; require $path;
return; return true;
}
}
}
/**
* Load a class that is stored in a module.
*
* @param string $file
* @return void
*/
private static function load_from_module($file)
{
// Since all module models and libraries must be namespaced to the
// module name, we'll extract the module name from the file.
$module = substr($file, 0, strpos($file, '/'));
if (in_array($module, static::$modules))
{
$module = MODULE_PATH.$module.'/';
// Slice the module name off of the filename. Even though module libraries
// and models are namespaced under the module, there will obviously not be
// a folder matching that namespace in the libraries or models directories
// of the module. Slicing it off will allow us to make a clean search for
// the relevant class file.
$file = substr($file, strpos($file, '/') + 1);
foreach (array($module.'models', $module.'libraries') as $directory)
{
if (file_exists($path = $directory.'/'.$file.EXT))
{
return require $path;
}
} }
} }
} }
......
...@@ -46,7 +46,7 @@ class Request { ...@@ -46,7 +46,7 @@ class Request {
} }
// Remove the application index page from the URI. // Remove the application index page from the URI.
if (strpos($uri, $index = '/'.Config::get('application.index')) === 0) if (strpos($uri, $index = '/index.php') === 0)
{ {
$uri = substr($uri, strlen($index)); $uri = substr($uri, strlen($index));
} }
......
<?php namespace System\Routing; <?php namespace System\Routing;
use System\Config;
class Loader { class Loader {
/** /**
...@@ -35,19 +37,17 @@ class Loader { ...@@ -35,19 +37,17 @@ class Loader {
*/ */
public function load($uri) public function load($uri)
{ {
return array_merge($this->load_nested_routes($uri), require $this->path.'routes'.EXT); return array_merge($this->load_nested_routes(explode('/', $uri)), require $this->path.'routes'.EXT);
} }
/** /**
* Load the appropriate routes from the routes directory. * Load the appropriate routes from the routes directory.
* *
* @param string $uri * @param array $segments
* @return array * @return array
*/ */
private function load_nested_routes($uri) private function load_nested_routes($segments)
{ {
$segments = explode('/', $uri);
// Work backwards through the URI segments until we find the deepest possible // Work backwards through the URI segments until we find the deepest possible
// matching route directory. Once we find it, we will return those routes. // matching route directory. Once we find it, we will return those routes.
foreach (array_reverse($segments, true) as $key => $value) foreach (array_reverse($segments, true) as $key => $value)
...@@ -75,19 +75,35 @@ class Loader { ...@@ -75,19 +75,35 @@ class Loader {
{ {
if ( ! is_null(static::$routes) and ! $reload) return static::$routes; if ( ! is_null(static::$routes) and ! $reload) return static::$routes;
$routes = require $path.'routes'.EXT; // Merge all of the module paths in with the specified path so that all
// active module routes will also be loaded. So, by default, this method
// will search the application path and all active module paths for routes.
$paths = array_merge(array($path), array_map(function($module) { return MODULE_PATH.$module.'/'; }, Config::get('application.modules')));
// Since route files can be nested deep within the route directory, we need to $routes = array();
// recursively spin through the directory to find every file.
$directoryIterator = new \RecursiveDirectoryIterator($path.'routes');
$recursiveIterator = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::SELF_FIRST); foreach ($paths as $path)
foreach ($recursiveIterator as $file)
{ {
if (filetype($file) === 'file' and strpos($file, EXT) !== false) if (file_exists($path.'routes'.EXT))
{
$routes = array_merge($routes, require $path.'routes'.EXT);
}
if (is_dir($path.'routes'))
{ {
$routes = array_merge(require $file, $routes); // Since route files can be nested deep within the route directory, we need to
// recursively spin through the directory to find every file.
$directoryIterator = new \RecursiveDirectoryIterator($path.'routes');
$recursiveIterator = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($recursiveIterator as $file)
{
if (filetype($file) === 'file' and strpos($file, EXT) !== false)
{
$routes = array_merge($routes, require $file);
}
}
} }
} }
......
...@@ -40,12 +40,12 @@ class Router { ...@@ -40,12 +40,12 @@ class Router {
* *
* @param string $method * @param string $method
* @param string $uri * @param string $uri
* @param array $routes * @param Loader $loader
* @return Router * @return Router
*/ */
public static function make($method, $uri, $routes = null) public static function make($method, $uri, $loader)
{ {
return new static($method, $uri, $routes); return new static($method, $uri, $loader);
} }
/** /**
......
...@@ -16,6 +16,13 @@ class View { ...@@ -16,6 +16,13 @@ class View {
*/ */
public $data = array(); public $data = array();
/**
* The module that contains the view.
*
* @var string
*/
public $module;
/** /**
* The path to the view. * The path to the view.
* *
...@@ -24,12 +31,19 @@ class View { ...@@ -24,12 +31,19 @@ class View {
public $path; public $path;
/** /**
* The view composers. * The defined view composers.
* *
* @var array * @var array
*/ */
private static $composers; private static $composers;
/**
* The defined view names.
*
* @var array
*/
private static $names;
/** /**
* Create a new view instance. * Create a new view instance.
* *
...@@ -39,15 +53,16 @@ class View { ...@@ -39,15 +53,16 @@ class View {
*/ */
public function __construct($view, $data = array()) public function __construct($view, $data = array())
{ {
$this->view = $view;
$this->data = $data; $this->data = $data;
if ( ! file_exists($path = VIEW_PATH.$view.EXT)) list($this->module, $this->path, $this->view) = static::parse($view);
if ( ! file_exists($this->path.$this->view.EXT))
{ {
throw new \Exception("View [$view] does not exist."); throw new \Exception("View [$view] does not exist.");
} }
$this->path = $path; $this->compose();
} }
/** /**
...@@ -59,33 +74,49 @@ class View { ...@@ -59,33 +74,49 @@ class View {
*/ */
public static function make($view, $data = array()) public static function make($view, $data = array())
{ {
if (is_null(static::$composers)) return new static($view, $data);
}
/**
* Parse a view identifier and get the module, path, and view name.
*
* @param string $view
* @return array
*/
private static function parse($view)
{
// Check for a module qualifier. If a module name is present, we need to extract it from
// the view name, otherwise, we will use "application" as the module.
$module = (strpos($view, '::') !== false) ? substr($view, 0, strpos($view, ':')) : 'application';
$path = ($module == 'application') ? VIEW_PATH : MODULE_PATH.$module.'/views/';
// If the view is stored in a module, we need to strip the module qualifier off
// of the view name before continuing.
if ($module != 'application')
{ {
static::$composers = require APP_PATH.'composers'.EXT; $view = substr($view, strpos($view, ':') + 2);
} }
$instance = new static($view, $data); return array($module, $path, str_replace('.', '/', $view));
return (isset(static::$composers[$view])) ? call_user_func(static::$composers[$view], $instance) : $instance;
} }
/** /**
* Create a new named view instance. * Call the composer for the view instance.
* *
* @param string $view * @return void
* @param array $data
* @return View
*/ */
public static function of($view, $data = array()) private function compose()
{ {
$views = Config::get('view.names'); if (is_null(static::$composers[$this->module]))
if ( ! array_key_exists($view, $views))
{ {
throw new \Exception("Named view [$view] is not defined."); static::$composers[$this->module] = (file_exists($path = $this->path.'composers'.EXT)) ? require $path : array();
} }
return static::make($views[$view], $data); if (isset(static::$composers[$this->module][$this->view]))
{
call_user_func(static::$composers[$this->module][$this->view], $this);
}
} }
/** /**
...@@ -107,7 +138,7 @@ class View { ...@@ -107,7 +138,7 @@ class View {
ob_start(); ob_start();
try { include $this->path; } catch (\Exception $e) { Error::handle($e); } try { include $this->path.$this->view.EXT; } catch (\Exception $e) { Error::handle($e); }
return ob_get_clean(); return ob_get_clean();
} }
...@@ -138,17 +169,6 @@ class View { ...@@ -138,17 +169,6 @@ class View {
return $this; return $this;
} }
/**
* Magic Method for creating named view instances.
*/
public static function __callStatic($method, $parameters)
{
if (strpos($method, 'of_') === 0)
{
return static::of(substr($method, 3), Arr::get($parameters, 0, array()));
}
}
/** /**
* Magic Method for getting items from the view data. * Magic Method for getting items from the view data.
*/ */
......
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