Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

548 lines
17 KiB

14 years ago
<?php
/**
* Module class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
/**
* Module is the base class for module and application classes.
*
13 years ago
* Module mainly manages application components and sub-modules that belongs to a module.
14 years ago
*
13 years ago
* @property string $uniqueId An ID that uniquely identifies this module among all modules within
* the current application.
13 years ago
* @property string $basePath The root directory of the module. Defaults to the directory containing the module class.
* @property array $modules The configuration of the currently installed modules (module ID => configuration).
* @property array $components The application components (indexed by their IDs).
* @property array $import List of aliases to be imported. This property is write-only.
* @property array $aliases List of aliases to be defined. This property is write-only.
*
14 years ago
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
13 years ago
abstract class Module extends Component implements Initable
14 years ago
{
/**
14 years ago
* @var array custom module parameters (name => value).
*/
public $params = array();
/**
13 years ago
* @var array the IDs of the application components that should be preloaded when this module is created.
14 years ago
*/
public $preload = array();
13 years ago
/**
* @var string an ID that uniquely identifies this module among other modules which have the same [[parent]].
*/
public $id;
/**
* @var Module the parent module of this module. Null if this module does not have a parent.
*/
public $module;
/**
* @var array mapping from controller ID to controller configurations.
* Each name-value pair specifies the configuration of a single controller.
* A controller configuration can be either a string or an array.
* If the former, the string should be the class name or path alias of the controller.
* If the latter, the array must contain a 'class' element which specifies
* the controller's class name or path alias, and the rest of the name-value pairs
* in the array are used to initialize the corresponding controller properties. For example,
*
* ~~~
* array(
* 'account' => '@application/controllers/UserController',
* 'article' => array(
* 'class' => '@application/controllers/PostController',
* 'pageTitle' => 'something new',
* ),
* )
* ~~~
*/
public $controllers = array();
/**
* @return string the default route of this module. Defaults to 'default'.
* The route may consist of child module ID, controller ID, and/or action ID.
* For example, `help`, `post/create`, `admin/post/create`.
* If action ID is not given, it will take the default value as specified in
* [[Controller::defaultAction]].
*/
public $defaultRoute = 'default';
/**
* @var string the root directory of the module.
* @see getBasePath
* @see setBasePath
*/
protected $_basePath;
/**
* @var string the directory containing controller classes in the module.
* @see getControllerPath
* @see setControllerPath
*/
protected $_controllerPath;
/**
* @var array child modules of this module
*/
protected $_modules = array();
/**
* @var array application components of this module
*/
protected $_components = array();
14 years ago
/**
* Constructor.
* @param string $id the ID of this module
13 years ago
* @param Module $parent the parent module (if any)
14 years ago
*/
13 years ago
public function __construct($id, $parent = null)
14 years ago
{
13 years ago
$this->id = $id;
$this->module = $parent;
14 years ago
}
/**
* Getter magic method.
* This method is overridden to support accessing application components
* like reading module properties.
* @param string $name application component or property name
* @return mixed the named property value
*/
public function __get($name)
{
14 years ago
if ($this->hasComponent($name)) {
14 years ago
return $this->getComponent($name);
13 years ago
} else {
14 years ago
return parent::__get($name);
14 years ago
}
14 years ago
}
/**
* Checks if a property value is null.
* This method overrides the parent implementation by checking
* if the named application component is loaded.
* @param string $name the property name or the event name
* @return boolean whether the property value is null
*/
public function __isset($name)
{
14 years ago
if ($this->hasComponent($name)) {
14 years ago
return $this->getComponent($name) !== null;
13 years ago
} else {
14 years ago
return parent::__isset($name);
14 years ago
}
}
/**
13 years ago
* Initializes the module.
* This method is called after the module is created and initialized with property values
13 years ago
* given in configuration. The default implement will create a path alias using the module [[id]]
* and then call [[preloadComponents()]] to load components that are declared in [[preload]].
14 years ago
*/
13 years ago
public function init()
14 years ago
{
13 years ago
\Yii::setAlias('@' . $this->id, $this->getBasePath());
13 years ago
$this->preloadComponents();
14 years ago
}
/**
13 years ago
* Returns an ID that uniquely identifies this module among all modules within the current application.
* @return string the unique ID of the module.
14 years ago
*/
13 years ago
public function getUniqueId()
14 years ago
{
13 years ago
if ($this->module && !$this->module instanceof Application) {
return $this->module->getUniqueId() . "/{$this->id}";
} else {
return $this->id;
}
14 years ago
}
/**
* Returns the root directory of the module.
* It defaults to the directory containing the module class file.
* @return string the root directory of the module.
14 years ago
*/
public function getBasePath()
{
14 years ago
if ($this->_basePath === null) {
13 years ago
$class = new \ReflectionClass($this);
14 years ago
$this->_basePath = dirname($class->getFileName());
}
return $this->_basePath;
}
/**
* Sets the root directory of the module.
* This method can only be invoked at the beginning of the constructor.
* @param string $path the root directory of the module. This can be either a directory name or a path alias.
14 years ago
* @throws Exception if the directory does not exist.
14 years ago
*/
public function setBasePath($path)
{
13 years ago
$p = \Yii::getAlias($path);
if ($p === false || !is_dir($p)) {
14 years ago
throw new Exception('Invalid base path: ' . $path);
13 years ago
} else {
13 years ago
$this->_basePath = realpath($p);
14 years ago
}
}
/**
* Returns the directory that contains the controller classes.
* Defaults to "[[basePath]]/controllers".
* @return string the directory that contains the controller classes.
*/
public function getControllerPath()
{
if ($this->_controllerPath !== null) {
return $this->_controllerPath;
} else {
return $this->_controllerPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'controllers';
}
}
/**
* Sets the directory that contains the controller classes.
* @param string $path the directory that contains the controller classes.
* This can be either a directory name or a path alias.
* @throws Exception if the directory is invalid
*/
public function setControllerPath($path)
{
$p = \Yii::getAlias($path);
if ($p === false || !is_dir($p)) {
throw new Exception('Invalid controller path: ' . $path);
} else {
$this->_controllerPath = realpath($p);
}
}
/**
14 years ago
* Imports the specified path aliases.
13 years ago
* This method is provided so that you can import a set of path aliases when configuring a module.
* The path aliases will be imported by calling [[\Yii::import()]].
14 years ago
* @param array $aliases list of path aliases to be imported
14 years ago
*/
public function setImport($aliases)
{
14 years ago
foreach ($aliases as $alias) {
\Yii::import($alias);
}
14 years ago
}
/**
14 years ago
* Defines path aliases.
13 years ago
* This method calls [[\Yii::setAlias()]] to register the path aliases.
* This method is provided so that you can define path aliases when configuring a module.
14 years ago
* @param array $aliases list of path aliases to be defined. The array keys are alias names
13 years ago
* (must start with '@') and the array values are the corresponding paths or aliases.
14 years ago
* For example,
14 years ago
*
* ~~~
14 years ago
* array(
13 years ago
* '@models' => '@app/models', // an existing alias
13 years ago
* '@backend' => __DIR__ . '/../backend', // a directory
14 years ago
* )
14 years ago
* ~~~
14 years ago
*/
14 years ago
public function setAliases($aliases)
14 years ago
{
14 years ago
foreach ($aliases as $name => $alias) {
\Yii::setAlias($name, $alias);
14 years ago
}
}
/**
13 years ago
* Checks whether the named module exists.
* @param string $id module ID
* @return boolean whether the named module exists. Both loaded and unloaded modules
* are considered.
14 years ago
*/
13 years ago
public function hasModule($id)
14 years ago
{
13 years ago
return isset($this->_modules[$id]);
}
/**
* Retrieves the named module.
* @param string $id module ID (case-sensitive)
* @param boolean $load whether to load the module if it is not yet loaded.
13 years ago
* @return Module|null the module instance, null if the module
* does not exist.
* @see hasModule()
*/
public function getModule($id, $load = true)
13 years ago
{
if (isset($this->_modules[$id])) {
if ($this->_modules[$id] instanceof Module) {
return $this->_modules[$id];
} elseif ($load) {
13 years ago
\Yii::trace("Loading \"$id\" module", __CLASS__);
return $this->_modules[$id] = \Yii::createObject($this->_modules[$id], $id, $this);
14 years ago
}
}
13 years ago
return null;
14 years ago
}
/**
13 years ago
* Adds a sub-module to this module.
* @param string $id module ID
* @param Module|array|null $module the sub-module to be added to this module. This can
* be one of the followings:
*
* - a [[Module]] object
* - a configuration array: when [[getModule()]] is called initially, the array
* will be used to instantiate the sub-module
* - null: the named sub-module will be removed from this module
14 years ago
*/
13 years ago
public function setModule($id, $module)
14 years ago
{
13 years ago
if ($module === null) {
unset($this->_modules[$id]);
} else {
$this->_modules[$id] = $module;
}
14 years ago
}
/**
13 years ago
* Returns the sub-modules in this module.
* @param boolean $loadedOnly whether to return the loaded sub-modules only. If this is set false,
* then all sub-modules registered in this module will be returned, whether they are loaded or not.
* Loaded modules will be returned as objects, while unloaded modules as configuration arrays.
* @return array the modules (indexed by their IDs)
14 years ago
*/
13 years ago
public function getModules($loadedOnly = false)
14 years ago
{
13 years ago
if ($loadedOnly) {
$modules = array();
foreach ($this->_modules as $module) {
if ($module instanceof Module) {
$modules[] = $module;
}
}
return $modules;
} else {
return $this->_modules;
}
14 years ago
}
/**
13 years ago
* Registers sub-modules in the current module.
14 years ago
*
13 years ago
* Each sub-module should be specified as a name-value pair, where
* name refers to the ID of the module and value the module or a configuration
* array that can be used to create the module. In the latter case, [[\Yii::createObject()]]
* will be used to create the module.
14 years ago
*
13 years ago
* If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
14 years ago
*
13 years ago
* The following is an example for registering two sub-modules:
14 years ago
*
13 years ago
* ~~~
* array(
* 'comment' => array(
* 'class' => 'app\modules\CommentModule',
* 'connectionID' => 'db',
* ),
* 'booking' => array(
* 'class' => 'app\modules\BookingModule',
* ),
* )
* ~~~
14 years ago
*
13 years ago
* @param array $modules modules (id => module configuration or instances)
14 years ago
*/
public function setModules($modules)
{
13 years ago
foreach ($modules as $id => $module) {
$this->_modules[$id] = $module;
14 years ago
}
}
14 years ago
/**
* Checks whether the named component exists.
* @param string $id application component ID
13 years ago
* @return boolean whether the named application component exists. Both loaded and unloaded components
* are considered.
14 years ago
*/
public function hasComponent($id)
{
13 years ago
return isset($this->_components[$id]);
14 years ago
}
/**
* Retrieves the named application component.
* @param string $id application component ID (case-sensitive)
* @param boolean $load whether to load the component if it is not yet loaded.
13 years ago
* @return ApplicationComponent|null the application component instance, null if the application component
* does not exist.
* @see hasComponent()
14 years ago
*/
public function getComponent($id, $load = true)
14 years ago
{
13 years ago
if (isset($this->_components[$id])) {
13 years ago
if ($this->_components[$id] instanceof ApplicationComponent) {
return $this->_components[$id];
} elseif ($load) {
13 years ago
\Yii::trace("Loading \"$id\" application component", __CLASS__);
return $this->_components[$id] = \Yii::createObject($this->_components[$id]);
14 years ago
}
}
13 years ago
return null;
14 years ago
}
/**
13 years ago
* Registers an application component in this module.
14 years ago
* @param string $id component ID
13 years ago
* @param ApplicationComponent|array|null $component the component to be added to the module. This can
* be one of the followings:
*
* - an [[ApplicationComponent]] object
* - a configuration array: when [[getComponent()]] is called initially for this component, the array
* will be used to instantiate the component
* - null: the named component will be removed from the module
14 years ago
*/
public function setComponent($id, $component)
{
13 years ago
if ($component === null) {
14 years ago
unset($this->_components[$id]);
13 years ago
} else {
14 years ago
$this->_components[$id] = $component;
}
}
/**
* Returns the application components.
* @param boolean $loadedOnly whether to return the loaded components only. If this is set false,
* then all components specified in the configuration will be returned, whether they are loaded or not.
* Loaded components will be returned as objects, while unloaded components as configuration arrays.
* @return array the application components (indexed by their IDs)
*/
13 years ago
public function getComponents($loadedOnly = false)
14 years ago
{
13 years ago
if ($loadedOnly) {
13 years ago
$components = array();
foreach ($this->_components as $component) {
if ($component instanceof ApplicationComponent) {
$components[] = $component;
}
}
return $components;
13 years ago
} else {
13 years ago
return $this->_components;
13 years ago
}
14 years ago
}
/**
13 years ago
* Registers a set of application components in this module.
14 years ago
*
13 years ago
* Each application component should be specified as a name-value pair, where
* name refers to the ID of the component and value the component or a configuration
* array that can be used to create the component. In the latter case, [[\Yii::createObject()]]
* will be used to create the component.
14 years ago
*
13 years ago
* If a new component has the same ID as an existing one, the existing one will be overwritten silently.
14 years ago
*
13 years ago
* The following is an example for setting two components:
*
* ~~~
14 years ago
* array(
13 years ago
* 'db' => array(
* 'class' => 'yii\db\dao\Connection',
* 'dsn' => 'sqlite:path/to/file.db',
* ),
* 'cache' => array(
* 'class' => 'yii\caching\DbCache',
* 'connectionID' => 'db',
* ),
14 years ago
* )
13 years ago
* ~~~
14 years ago
*
13 years ago
* @param array $components application components (id => component configuration or instance)
14 years ago
*/
13 years ago
public function setComponents($components)
14 years ago
{
13 years ago
foreach ($components as $id => $component) {
$this->_components[$id] = $component;
14 years ago
}
}
/**
13 years ago
* Loads application components that are declared in [[preload]].
14 years ago
*/
14 years ago
public function preloadComponents()
14 years ago
{
13 years ago
foreach ($this->preload as $id) {
14 years ago
$this->getComponent($id);
13 years ago
}
14 years ago
}
/**
13 years ago
* Creates a controller instance based on the given route.
* This method tries to parse the given route (e.g. `post/create`) using the following algorithm:
*
* 1. Get the first segment in route
* 2. If the segment matches
* - an ID in [[controllers]], create a controller instance using the corresponding configuration,
* and return the controller with the rest part of the route;
13 years ago
* - an ID in [[modules]], call the [[createController()]] method of the corresponding module.
* - a controller class under [[controllerPath]], create the controller instance, and return it
* with the rest part of the route;
*
* @param string $route the route which may consist module ID, controller ID and/or action ID (e.g. `post/create`)
13 years ago
* @return array|boolean the array of controller instance and action ID. False if the route cannot be resolved.
*/
13 years ago
public function createController($route)
{
if (($route = trim($route, '/')) === '') {
$route = $this->defaultRoute;
}
if (($pos = strpos($route, '/')) !== false) {
$id = substr($route, 0, $pos);
$route = (string)substr($route, $pos + 1);
} else {
$id = $route;
$route = '';
}
// Controller IDs must start with a lower-case letter and consist of word characters only
if (!preg_match('/^[a-z][a-zA-Z0-9_]*$/', $id)) {
13 years ago
return false;
}
if (isset($this->controllers[$id])) {
13 years ago
return array(
\Yii::createObject($this->controllers[$id], $id, $this),
$route,
);
}
13 years ago
if (($module = $this->getModule($id)) !== null) {
$result = $module->createController($route);
if ($result !== false) {
return $result;
}
}
$className = ucfirst($id) . 'Controller';
$classFile = $this->getControllerPath() . DIRECTORY_SEPARATOR . $className . '.php';
if (is_file($classFile)) {
if (!class_exists($className, false)) {
require($classFile);
}
if (class_exists($className, false) && is_subclass_of($className, '\yii\base\Controller')) {
13 years ago
return array(
$className::newInstance(array(), $id, $this),
$route,
);
}
}
13 years ago
return false;
}
14 years ago
}