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.

622 lines
19 KiB

14 years ago
<?php
/**
* Module class file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
14 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\base;
12 years ago
use Yii;
use yii\util\StringHelper;
13 years ago
use yii\util\FileHelper;
14 years ago
/**
* Module is the base class for module and application classes.
*
* A module represents a sub-application which contains MVC elements by itself, such as
* models, views, controllers, etc.
*
* A module may consist of [[modules|sub-modules]].
*
* [[components|Components]] may be registered with the module so that they are globally
* accessible within the 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 components (indexed by their IDs) registered within this module.
13 years ago
* @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
*/
abstract class Module extends Component
14 years ago
{
/**
14 years ago
* @var array custom module parameters (name => value).
*/
public $params = array();
/**
* @var array the IDs of the components that should be preloaded when this module is created.
14 years ago
*/
public $preload = array();
13 years ago
/**
12 years ago
* @var string an ID that uniquely identifies this module among other modules which have the same [[module|parent]].
13 years ago
*/
public $id;
/**
* @var Module the parent module of this module. Null if this module does not have a parent.
*/
public $module;
/**
12 years ago
* @var string|boolean the layout that should be applied for views within this module. This refers to a view name
13 years ago
* relative to [[layoutPath]]. If this is not set, it means the layout value of the [[module|parent module]]
* will be taken. If this is false, layout will be disabled within this module.
*/
public $layout;
/**
* @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',
* ),
* )
* ~~~
*/
12 years ago
public $controllerMap = array();
/**
* @var string the namespace that controller classes are in. Default is to use global namespace.
*/
public $controllerNamespace;
/**
* @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.
*/
private $_basePath;
/**
12 years ago
* @var string the root directory that contains view files for this module
13 years ago
*/
private $_viewPath;
13 years ago
/**
12 years ago
* @var string the root directory that contains layout view files for this module.
13 years ago
*/
private $_layoutPath;
13 years ago
/**
* @var string the directory containing controller classes in the module.
*/
private $_controllerPath;
/**
* @var array child modules of this module
*/
private $_modules = array();
/**
* @var array components registered under this module
*/
private $_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)
* @param array $config name-value pairs that will be used to initialize the object properties
14 years ago
*/
public function __construct($id, $parent = null, $config = array())
14 years ago
{
13 years ago
$this->id = $id;
$this->module = $parent;
parent::__construct($config);
14 years ago
}
/**
* Getter magic method.
* This method is overridden to support accessing components
14 years ago
* like reading module properties.
* @param string $name component or property name
14 years ago
* @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 component is loaded.
14 years ago
* @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
{
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.
12 years ago
* Note that if the module is an application, an empty string will be returned.
13 years ago
* @return string the unique ID of the module.
14 years ago
*/
13 years ago
public function getUniqueId()
14 years ago
{
12 years ago
if ($this instanceof Application) {
return '';
} elseif ($this->module) {
return $this->module->getUniqueId() . '/' . $this->id;
13 years ago
} 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
$this->_basePath = FileHelper::ensureDirectory($path);
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)
{
13 years ago
$this->_controllerPath = FileHelper::ensureDirectory($path);
}
/**
13 years ago
* @return string the root directory of view files. Defaults to 'moduleDir/views' where
* moduleDir is the directory containing the module class.
*/
public function getViewPath()
{
if ($this->_viewPath !== null) {
return $this->_viewPath;
} else {
return $this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
}
}
/**
13 years ago
* Sets the directory that contains the view files.
13 years ago
* @param string $path the root directory of view files.
13 years ago
* @throws Exception if the directory is invalid
13 years ago
*/
public function setViewPath($path)
{
13 years ago
$this->_viewPath = FileHelper::ensureDirectory($path);
13 years ago
}
/**
* @return string the root directory of layout files. Defaults to 'moduleDir/views/layouts' where
* moduleDir is the directory containing the module class.
*/
public function getLayoutPath()
{
if ($this->_layoutPath !== null) {
return $this->_layoutPath;
} else {
return $this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
}
}
/**
13 years ago
* Sets the directory that contains the layout files.
13 years ago
* @param string $path the root directory of layout files.
13 years ago
* @throws Exception if the directory is invalid
13 years ago
*/
public function setLayoutPath($path)
{
13 years ago
$this->_layoutPath = FileHelper::ensureDirectory($path);
13 years ago
}
/**
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
}
/**
14 years ago
* Defines path aliases.
* This method calls [[Yii::setAlias()]] to register the path aliases.
13 years ago
* 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(
* '@models' => '@application/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) {
Yii::trace("Loading module: $id", __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()]]
13 years ago
* 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 component ID
* @return boolean whether the named component exists. Both loaded and unloaded components
13 years ago
* are considered.
14 years ago
*/
public function hasComponent($id)
{
13 years ago
return isset($this->_components[$id]);
14 years ago
}
/**
* Retrieves the named component.
* @param string $id component ID (case-sensitive)
* @param boolean $load whether to load the component if it is not yet loaded.
* @return Component|null the component instance, null if the component does not exist.
13 years ago
* @see hasComponent()
14 years ago
*/
public function getComponent($id, $load = true)
14 years ago
{
13 years ago
if (isset($this->_components[$id])) {
if ($this->_components[$id] instanceof Component) {
13 years ago
return $this->_components[$id];
} elseif ($load) {
Yii::trace("Loading component: $id", __CLASS__);
return $this->_components[$id] = Yii::createObject($this->_components[$id]);
14 years ago
}
}
13 years ago
return null;
14 years ago
}
/**
* Registers a component with this module.
14 years ago
* @param string $id component ID
* @param Component|array|null $component the component to be registered with the module. This can
13 years ago
* be one of the followings:
*
* - a [[Component]] object
13 years ago
* - a configuration array: when [[getComponent()]] is called initially for this component, the array
* will be used to instantiate the component via [[Yii::createObject()]].
13 years ago
* - 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 registered components.
14 years ago
* @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 components (indexed by their IDs)
14 years ago
*/
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 Component) {
13 years ago
$components[] = $component;
}
}
return $components;
13 years ago
} else {
13 years ago
return $this->_components;
13 years ago
}
14 years ago
}
/**
* Registers a set of components in this module.
14 years ago
*
* Each component should be specified as a name-value pair, where
13 years ago
* 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()]]
13 years ago
* 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\Connection',
13 years ago
* 'dsn' => 'sqlite:path/to/file.db',
* ),
* 'cache' => array(
* 'class' => 'yii\caching\DbCache',
* 'connectionID' => 'db',
* ),
14 years ago
* )
13 years ago
* ~~~
14 years ago
*
* @param array $components 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
}
}
/**
* Loads 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
}
12 years ago
/**
* Runs a controller action specified by a route.
* This method parses the specified route and creates the corresponding child module(s), controller and action
* instances. It then calls [[Controller::runAction()]] to run the action with the given parameters.
* If the route is empty, the method will use [[defaultRoute]].
12 years ago
* @param string $route the route that specifies the action.
* @param array $params the parameters to be passed to the action
* @return integer the status code returned by the action execution. 0 means normal, and other values mean abnormal.
* @throws InvalidRouteException if the requested route cannot be resolved into an action successfully
12 years ago
*/
public function runAction($route, $params = array())
{
$route = trim($route, '/');
if ($route === '') {
$route = trim($this->defaultRoute, '/');
}
if (($pos = strpos($route, '/')) !== false) {
$id = substr($route, 0, $pos);
$route2 = substr($route, $pos + 1);
12 years ago
} else {
$id = $route;
$route2 = '';
12 years ago
}
$module = $this->getModule($id);
if ($module !== null) {
return $module->runAction($route2, $params);
12 years ago
}
$controller = $this->createController($id);
if ($controller !== null) {
$oldController = Yii::$application->controller;
Yii::$application->controller = $controller;
12 years ago
$status = $controller->runAction($route2, $params);
12 years ago
Yii::$application->controller = $oldController;
return $status;
} else {
throw new InvalidRouteException('Unable to resolve the request: ' . $this->getUniqueId() . '/' . $route);
}
12 years ago
}
/**
* Creates a controller instance based on the controller ID.
*
* The controller is created within the given module. The method first attempts to
* create the controller based on the [[controllerMap]] of the module. If not available,
* it will look for the controller class under the [[controllerPath]] and create an
* instance of it.
*
* @param string $id the controller ID
* @return Controller the newly created controller instance
*/
public function createController($id)
{
if (isset($this->controllerMap[$id])) {
return Yii::createObject($this->controllerMap[$id], $id, $this);
} elseif (preg_match('/^[a-z0-9\\-_]+$/', $id)) {
$className = StringHelper::id2camel($id) . 'Controller';
$classFile = $this->controllerPath . DIRECTORY_SEPARATOR . $className . '.php';
if (is_file($classFile)) {
$className = $this->controllerNamespace . '\\' . $className;
if (!class_exists($className, false)) {
require($classFile);
}
if (class_exists($className, false) && is_subclass_of($className, '\yii\base\Controller')) {
return new $className($id, $this);
}
}
}
return null;
}
14 years ago
}