Application represents a console application.
Application extends from yii\base\Application by providing functionalities that are specific to console requests. In particular, it deals with console requests through a command-based approach:
The command classes should be under the namespace specified by $controllerNamespace. Their naming should follow the same naming convention as controllers. For example, the help
command is implemented using the HelpController
class.
To run the console application, enter the following on the command line:
yii <route> [--param1=value1 --param2 ...]
where <route>
refers to a controller route in the form of ModuleID/ControllerID/ActionID
(e.g. sitemap/create
), and param1
, param2
refers to a set of named parameters that will be used to initialize the controller action (e.g. --since=0
specifies a since
parameter whose value is 0 and a corresponding $since
parameter is passed to the action method).
A help
command is provided by default, which lists available commands and shows their usage. To use this command, simply type:
yii help
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Constructor.
public function __construct($config = [])
{
$config = $this->loadConfig($config);
parent::__construct($config);
}
public mixed __get ( $name ) $name string
Component or property name
return mixedThe named property value
public function __get($name)
{
if ($this->has($name)) {
return $this->get($name);
}
return parent::__get($name);
}
Defined in: yii\di\ServiceLocator::__isset()
Checks if a property value is null.
This method overrides the parent implementation by checking if the named component is loaded.
public function __isset($name)
{
if ($this->has($name)) {
return true;
}
return parent::__isset($name);
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;
.
See also __get().
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
$name = trim(substr($name, 3));
if ($value instanceof Behavior) {
$this->attachBehavior($name, $value);
} elseif ($value instanceof \Closure) {
$this->attachBehavior($name, call_user_func($value));
} elseif (isset($value['__class']) && is_subclass_of($value['__class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (!isset($value['__class']) && isset($value['class']) && is_subclass_of($value['class'], Behavior::class)) {
$this->attachBehavior($name, Yii::createObject($value));
} elseif (is_string($value) && is_subclass_of($value, Behavior::class, true)) {
$this->attachBehavior($name, Yii::createObject($value));
} else {
throw new InvalidConfigException('Class is not of type ' . Behavior::class . ' or its subclasses');
}
return;
}
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property)
.
See also https://www.php.net/manual/en/function.unset.php.
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Module::afterAction()
This method is invoked right after an action within this module is executed.
The method will trigger the EVENT_AFTER_ACTION event. The return value of the method will be used as the action return value.
If you override this method, your code should look like the following:
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
return $result;
}
public mixed afterAction ( $action, $result ) $action yii\base\Action
The action just executed.
$result mixedThe action return result.
return mixedThe processed action result.
public function afterAction($action, $result)
{
$event = new ActionEvent($action);
$event->result = $result;
$this->trigger(self::EVENT_AFTER_ACTION, $event);
return $event->result;
}
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
public void attachBehaviors ( $behaviors ) $behaviors array
List of behaviors to be attached to the component
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Module::beforeAction()
This method is invoked right before an action within this module is executed.
The method will trigger the EVENT_BEFORE_ACTION event. The return value of the method will determine whether the action should continue to run.
In case the action should not run, the request should be handled inside of the beforeAction
code by either providing the necessary output or redirecting the request. Otherwise the response will be empty.
If you override this method, your code should look like the following:
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
return true;
}
public function beforeAction($action)
{
$event = new ActionEvent($action);
$this->trigger(self::EVENT_BEFORE_ACTION, $event);
return $event->isValid;
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public function behaviors()
{
return [];
}
Defined in: yii\base\Application::bootstrap()
Initializes extensions and executes bootstrap components.
This method is called by init() after the application has been fully configured. If you override this method, make sure you also call the parent implementation.
protected function bootstrap()
{
if ($this->extensions === null) {
$file = Yii::getAlias('@vendor/yiisoft/extensions.php');
$this->extensions = is_file($file) ? include $file : [];
}
foreach ($this->extensions as $extension) {
if (!empty($extension['alias'])) {
foreach ($extension['alias'] as $name => $path) {
Yii::setAlias($name, $path);
}
}
if (isset($extension['bootstrap'])) {
$component = Yii::createObject($extension['bootstrap']);
if ($component instanceof BootstrapInterface) {
Yii::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
$component->bootstrap($this);
} else {
Yii::debug('Bootstrap with ' . get_class($component), __METHOD__);
}
}
}
foreach ($this->bootstrap as $mixed) {
$component = null;
if ($mixed instanceof \Closure) {
Yii::debug('Bootstrap with Closure', __METHOD__);
if (!$component = call_user_func($mixed, $this)) {
continue;
}
} elseif (is_string($mixed)) {
if ($this->has($mixed)) {
$component = $this->get($mixed);
} elseif ($this->hasModule($mixed)) {
$component = $this->getModule($mixed);
} elseif (strpos($mixed, '\\') === false) {
throw new InvalidConfigException("Unknown bootstrapping component ID: $mixed");
}
}
if (!isset($component)) {
$component = Yii::createObject($mixed);
}
if ($component instanceof BootstrapInterface) {
Yii::debug('Bootstrap with ' . get_class($component) . '::bootstrap()', __METHOD__);
$component->bootstrap($this);
} else {
Yii::debug('Bootstrap with ' . get_class($component), __METHOD__);
}
}
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
$checkVars
is true);$checkBehaviors
is true).See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether the property can be read
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
$checkVars
is true);$checkBehaviors
is true).See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether the property can be written
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Deprecated since 2.0.14. On PHP >=5.5, use ::class
instead.
public static function className()
{
return get_called_class();
}
public function clear($id)
{
unset($this->_definitions[$id], $this->_components[$id]);
}
Returns the configuration of the built-in commands.
public function coreCommands()
{
return [
'asset' => 'yii\console\controllers\AssetController',
'cache' => 'yii\console\controllers\CacheController',
'fixture' => 'yii\console\controllers\FixtureController',
'help' => 'yii\console\controllers\HelpController',
'message' => 'yii\console\controllers\MessageController',
'migrate' => 'yii\console\controllers\MigrateController',
'serve' => 'yii\console\controllers\ServeController',
];
}
Returns the configuration of core application components.
public function coreComponents()
{
return array_merge(parent::coreComponents(), [
'request' => ['class' => 'yii\console\Request'],
'response' => ['class' => 'yii\console\Response'],
'errorHandler' => ['class' => 'yii\console\ErrorHandler'],
]);
}
Defined in: yii\base\Module::createController()
Creates a controller instance based on the given route.
The route should be relative to this module. The method implements the following algorithm to resolve the given route:
createController()
with the rest part of the route;abc/def/xyz
. Try either abc\DefController
or abc\def\XyzController
class within the controller namespace.If any of the above steps resolves into a controller, it is returned together with the rest part of the route which will be treated as the action ID. Otherwise, false
will be returned.
public function createController($route)
{
if ($route === '') {
$route = $this->defaultRoute;
}
$route = trim($route, '/');
if (strpos($route, '//') !== false) {
return false;
}
if (strpos($route, '/') !== false) {
list($id, $route) = explode('/', $route, 2);
} else {
$id = $route;
$route = '';
}
if (isset($this->controllerMap[$id])) {
$controller = Yii::createObject($this->controllerMap[$id], [$id, $this]);
return [$controller, $route];
}
$module = $this->getModule($id);
if ($module !== null) {
return $module->createController($route);
}
if (($pos = strrpos($route, '/')) !== false) {
$id .= '/' . substr($route, 0, $pos);
$route = substr($route, $pos + 1);
}
$controller = $this->createControllerByID($id);
if ($controller === null && $route !== '') {
$controller = $this->createControllerByID($id . '/' . $route);
$route = '';
}
return $controller === null ? false : [$controller, $route];
}
public function createControllerByID($id)
{
$pos = strrpos($id, '/');
if ($pos === false) {
$prefix = '';
$className = $id;
} else {
$prefix = substr($id, 0, $pos + 1);
$className = substr($id, $pos + 1);
}
if ($this->isIncorrectClassNameOrPrefix($className, $prefix)) {
return null;
}
$className = preg_replace_callback('%-([a-z0-9_])%i', function ($matches) {
return ucfirst($matches[1]);
}, ucfirst($className)) . 'Controller';
$className = ltrim($this->controllerNamespace . '\\' . str_replace('/', '\\', $prefix) . $className, '\\');
if (strpos($className, '-') !== false || !class_exists($className)) {
return null;
}
if (is_subclass_of($className, 'yii\base\Controller')) {
$controller = Yii::createObject($className, [$id, $this]);
return get_class($controller) === $className ? $controller : null;
} elseif (YII_DEBUG) {
throw new InvalidConfigException('Controller class must extend from \\yii\\base\\Controller.');
}
return null;
}
protected function defaultVersion()
{
if ($this->module === null) {
return '1.0';
}
return $this->module->getVersion();
}
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Application::end()
Terminates the application.
This method replaces the exit()
function by ensuring the application life cycle is completed before terminating the application.
The exit status (value 0 means normal exit while other values mean abnormal exit).
$response yii\base\Response|nullThe response to be sent. If not set, the default application $response component will be used.
throws yii\base\ExitExceptionif the application is in testing mode
public function end($status = 0, $response = null)
{
if ($this->state === self::STATE_BEFORE_REQUEST || $this->state === self::STATE_HANDLING_REQUEST) {
$this->state = self::STATE_AFTER_REQUEST;
$this->trigger(self::EVENT_AFTER_REQUEST);
}
if ($this->state !== self::STATE_SENDING_RESPONSE && $this->state !== self::STATE_END) {
$this->state = self::STATE_END;
$response = $response ?: $this->getResponse();
$response->send();
}
if (YII_ENV_TEST) {
throw new ExitException($status);
}
exit($status);
}
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Defined in: yii\base\Module::get()
Returns the component instance with the specified ID.
Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module. The parent module may be the application.
public object|null get ( $id, $throwException = true ) $id stringComponent ID (e.g. db
).
Whether to throw an exception if $id
is not registered with the locator before.
The component of the specified ID. If $throwException
is false and $id
is not registered before, null will be returned.
if $id
refers to a nonexistent component ID
public function get($id, $throwException = true)
{
if (!isset($this->module)) {
return parent::get($id, $throwException);
}
$component = parent::get($id, false);
if ($component === null) {
$component = $this->module->get($id, $throwException);
}
return $component;
}
public function getAssetManager()
{
return $this->get('assetManager');
}
public function getAuthManager()
{
return $this->get('authManager', false);
}
public function getBasePath()
{
if ($this->_basePath === null) {
$class = new \ReflectionClass($this);
$this->_basePath = dirname($class->getFileName());
}
return $this->_basePath;
}
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
public function getCache()
{
return $this->get('cache', false);
}
public array getComponents ( $returnDefinitions = true ) $returnDefinitions boolean
Whether to return component definitions instead of the loaded component instances.
return arrayThe list of the component definitions or the loaded component instances (ID => definition or instance).
public function getComponents($returnDefinitions = true)
{
return $returnDefinitions ? $this->_definitions : $this->_components;
}
public function getControllerPath()
{
if ($this->_controllerPath === null) {
$this->_controllerPath = Yii::getAlias('@' . str_replace('\\', '/', $this->controllerNamespace));
}
return $this->_controllerPath;
}
public function getDb()
{
return $this->get('db');
}
Returns the error handler component.
public function getErrorHandler()
{
return $this->get('errorHandler');
}
public function getFormatter()
{
return $this->get('formatter');
}
public function getI18n()
{
return $this->get('i18n');
}
Defined in: yii\base\Module::getInstance()
Returns the currently requested instance of this module class.
If the module class is not currently requested, null
will be returned. This method is provided so that you access the module instance from anywhere within the module.
The currently requested instance of this module class, or null
if the module class is not requested.
public static function getInstance()
{
$class = get_called_class();
return isset(Yii::$app->loadedModules[$class]) ? Yii::$app->loadedModules[$class] : null;
}
public function getLayoutPath()
{
if ($this->_layoutPath === null) {
$this->_layoutPath = $this->getViewPath() . DIRECTORY_SEPARATOR . 'layouts';
}
return $this->_layoutPath;
}
public function getLog()
{
return $this->get('log');
}
public function getMailer()
{
return $this->get('mailer');
}
public yii\base\Module|null getModule ( $id, $load = true ) $id string
Module ID (case-sensitive). To retrieve grand child modules, use ID path relative to this module (e.g. admin/content
).
Whether to load the module if it is not yet loaded.
return yii\base\Module|nullThe module instance, null
if the module does not exist.
public function getModule($id, $load = true)
{
if (($pos = strpos($id, '/')) !== false) {
$module = $this->getModule(substr($id, 0, $pos));
return $module === null ? null : $module->getModule(substr($id, $pos + 1), $load);
}
if (isset($this->_modules[$id])) {
if ($this->_modules[$id] instanceof self) {
return $this->_modules[$id];
} elseif ($load) {
Yii::debug("Loading module: $id", __METHOD__);
$module = Yii::createObject($this->_modules[$id], [$id, $this]);
$module::setInstance($module);
return $this->_modules[$id] = $module;
}
}
return null;
}
public array getModules ( $loadedOnly = false ) $loadedOnly boolean
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.
The modules (indexed by their IDs).
public function getModules($loadedOnly = false)
{
if ($loadedOnly) {
$modules = [];
foreach ($this->_modules as $module) {
if ($module instanceof self) {
$modules[] = $module;
}
}
return $modules;
}
return $this->_modules;
}
Returns the request component.
public function getRequest()
{
return $this->get('request');
}
Returns the response component.
public function getResponse()
{
return $this->get('response');
}
public function getRuntimePath()
{
if ($this->_runtimePath === null) {
$this->setRuntimePath($this->getBasePath() . DIRECTORY_SEPARATOR . 'runtime');
}
return $this->_runtimePath;
}
public function getSecurity()
{
return $this->get('security');
}
public function getTimeZone()
{
return date_default_timezone_get();
}
Defined in: yii\base\Application::getUniqueId()
Returns an ID that uniquely identifies this module among all modules within the current application.
Since this is an application instance, it will always return an empty string.
public function getUniqueId()
{
return '';
}
public function getUrlManager()
{
return $this->get('urlManager');
}
public function getVendorPath()
{
if ($this->_vendorPath === null) {
$this->setVendorPath($this->getBasePath() . DIRECTORY_SEPARATOR . 'vendor');
}
return $this->_vendorPath;
}
public function getVersion()
{
if ($this->_version === null) {
$this->_version = $this->defaultVersion();
} else {
if (!is_scalar($this->_version)) {
$this->_version = call_user_func($this->_version, $this);
}
}
return $this->_version;
}
public function getView()
{
return $this->get('view');
}
public function getViewPath()
{
if ($this->_viewPath === null) {
$this->_viewPath = $this->getBasePath() . DIRECTORY_SEPARATOR . 'views';
}
return $this->_viewPath;
}
Handles the specified request.
public function handleRequest($request)
{
list($route, $params) = $request->resolve();
$this->requestedRoute = $route;
$result = $this->runAction($route, $params);
if ($result instanceof Response) {
return $result;
}
$response = $this->getResponse();
$response->exitStatus = $result;
return $response;
}
Defined in: yii\base\Module::has()
Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
Since version 2.0.13, if a component isn't defined in the module, it will be looked up in the parent module. The parent module may be the application.
This method may return different results depending on the value of $checkInstance
.
$checkInstance
is false (default), the method will return a value indicating whether the locator has the specified component definition.$checkInstance
is true, the method will return a value indicating whether the locator has instantiated the specified component.Component ID (e.g. db
).
Whether the method should check if the component is shared and instantiated.
return booleanWhether the locator has the specified component definition or has instantiated the component.
public function has($id, $checkInstance = false)
{
return parent::has($id, $checkInstance) || (isset($this->module) && $this->module->has($id, $checkInstance));
}
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
$checkBehaviors
is true).The property name
$checkBehaviors booleanWhether to treat behaviors' methods as methods of this component
return booleanWhether the method is defined
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Module::hasModule()
Checks whether the child module of the specified ID exists.
This method supports checking the existence of both child and grand child modules.
public boolean hasModule ( $id ) $id stringModule ID. For grand child modules, use ID path relative to this module (e.g. admin/content
).
Whether the named module exists. Both loaded and unloaded modules are considered.
public function hasModule($id)
{
if (($pos = strpos($id, '/')) !== false) {
$module = $this->getModule(substr($id, 0, $pos));
return $module === null ? false : $module->hasModule(substr($id, $pos + 1));
}
return isset($this->_modules[$id]);
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
$checkVars
is true);$checkBehaviors
is true).See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) $name stringThe property name
$checkVars booleanWhether to treat member variables as properties
$checkBehaviors booleanWhether to treat behaviors' properties as properties of this component
return booleanWhether the property is defined
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Initialize the application.
public function init()
{
parent::init();
if ($this->enableCoreCommands) {
foreach ($this->coreCommands() as $id => $command) {
if (!isset($this->controllerMap[$id])) {
$this->controllerMap[$id] = $command;
}
}
}
if (!isset($this->controllerMap['help'])) {
$this->controllerMap['help'] = 'yii\console\controllers\HelpController';
}
}
Loads the configuration.
This method will check if the command line option OPTION_APPCONFIG is specified. If so, the corresponding file will be loaded as the application configuration. Otherwise, the configuration provided as the parameter will be returned back.
protected array loadConfig ( $config ) $config arrayThe configuration provided in the constructor.
return arrayThe actual configuration to be used by the application.
protected function loadConfig($config)
{
if (!empty($_SERVER['argv'])) {
$option = '--' . self::OPTION_APPCONFIG . '=';
foreach ($_SERVER['argv'] as $param) {
if (strpos($param, $option) !== false) {
$path = substr($param, strlen($option));
if (!empty($path) && is_file($file = Yii::getAlias($path))) {
return require $file;
}
exit("The configuration file does not exist: $path\n");
}
}
}
return $config;
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) $name stringEvent name
$handler callable|nullThe event handler to be removed. If it is null, all handlers attached to the named event will be removed.
return booleanIf a handler is found and detached
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... }
[$object, 'handleClick']
['Page', 'handleClick']
'handleClick'
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) $name stringThe event name
$handler callableThe event handler
$data mixedThe data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data.
$append booleanWhether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
Defined in: yii\base\Application::preInit()
Pre-initializes the application.
This method is called at the beginning of the application constructor. It initializes several important application properties. If you override this method, please make sure you call the parent implementation.
public function preInit(&$config)
{
if (!isset($config['id'])) {
throw new InvalidConfigException('The "id" configuration for the Application is required.');
}
if (isset($config['basePath'])) {
$this->setBasePath($config['basePath']);
unset($config['basePath']);
} else {
throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
}
if (isset($config['vendorPath'])) {
$this->setVendorPath($config['vendorPath']);
unset($config['vendorPath']);
} else {
$this->getVendorPath();
}
if (isset($config['runtimePath'])) {
$this->setRuntimePath($config['runtimePath']);
unset($config['runtimePath']);
} else {
$this->getRuntimePath();
}
if (isset($config['timeZone'])) {
$this->setTimeZone($config['timeZone']);
unset($config['timeZone']);
} elseif (!ini_get('date.timezone')) {
$this->setTimeZone('UTC');
}
if (isset($config['container'])) {
$this->setContainer($config['container']);
unset($config['container']);
}
foreach ($this->coreComponents() as $id => $component) {
if (!isset($config['components'][$id])) {
$config['components'][$id] = $component;
} elseif (is_array($config['components'][$id]) && !isset($config['components'][$id]['class'])) {
$config['components'][$id]['class'] = $component['class'];
}
}
}
protected function registerErrorHandler(&$config)
{
if (YII_ENABLE_ERROR_HANDLER) {
if (!isset($config['components']['errorHandler']['class'])) {
echo "Error: no errorHandler component is configured.\n";
exit(1);
}
$this->set('errorHandler', $config['components']['errorHandler']);
unset($config['components']['errorHandler']);
$this->getErrorHandler()->register();
}
}
public integer run ( ) return integer
The exit status (0 means normal, non-zero values mean abnormal)
public function run()
{
try {
$this->state = self::STATE_BEFORE_REQUEST;
$this->trigger(self::EVENT_BEFORE_REQUEST);
$this->state = self::STATE_HANDLING_REQUEST;
$response = $this->handleRequest($this->getRequest());
$this->state = self::STATE_AFTER_REQUEST;
$this->trigger(self::EVENT_AFTER_REQUEST);
$this->state = self::STATE_SENDING_RESPONSE;
$response->send();
$this->state = self::STATE_END;
return $response->exitStatus;
} catch (ExitException $e) {
$this->end($e->statusCode, isset($response) ? $response : null);
return $e->statusCode;
}
}
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 yii\console\Controller::runAction() to run the action with the given parameters. If the route is empty, the method will use $defaultRoute.
For example, to run public function actionTest($a, $b)
assuming that the controller has options the following code should be used:
\Yii::$app->runAction('controller/test', ['option' => 'value', $a, $b]);
public function runAction($route, $params = [])
{
try {
$res = parent::runAction($route, $params);
return is_object($res) ? $res : (int) $res;
} catch (InvalidRouteException $e) {
throw new UnknownCommandException($route, $this, 0, $e);
}
}
Defined in: yii\di\ServiceLocator::set()
Registers a component definition with this locator.
For example,
$locator->set('cache', 'yii\caching\FileCache');
$locator->set('db', [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
$locator->set('cache', function ($params) {
return new \yii\caching\FileCache;
});
$locator->set('cache', new \yii\caching\FileCache);
If a component definition with the same ID already exists, it will be overwritten.
public void set ( $id, $definition ) $id stringComponent ID (e.g. db
).
The component definition to be registered with this locator. It can be one of the following:
class
element is required and stands for the the class of the object to be created.['Foo', 'bar']
). The callable will be called by get() to return an object associated with the specified component ID.if the definition is an invalid configuration array
public function set($id, $definition)
{
unset($this->_components[$id]);
if ($definition === null) {
unset($this->_definitions[$id]);
return;
}
if (is_object($definition) || is_callable($definition, true)) {
$this->_definitions[$id] = $definition;
} elseif (is_array($definition)) {
if (isset($definition['__class'])) {
$this->_definitions[$id] = $definition;
$this->_definitions[$id]['class'] = $definition['__class'];
unset($this->_definitions[$id]['__class']);
} elseif (isset($definition['class'])) {
$this->_definitions[$id] = $definition;
} else {
throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
}
} else {
throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
}
}
public void setAliases ( $aliases ) $aliases array
List of path aliases to be defined. The array keys are alias names (must start with @
) and the array values are the corresponding paths or aliases. For example,
[
'@models' => '@app/models',
'@backend' => __DIR__ . '/../backend',
]
public function setAliases($aliases)
{
foreach ($aliases as $name => $alias) {
Yii::setAlias($name, $alias);
}
}
Defined in: yii\base\Application::setBasePath()
Sets the root directory of the application and the @app alias.
This method can only be invoked at the beginning of the constructor.
public function setBasePath($path)
{
parent::setBasePath($path);
Yii::setAlias('@app', $this->getBasePath());
}
Defined in: yii\di\ServiceLocator::setComponents()
Registers a set of component definitions in this locator.
This is the bulk version of set(). The parameter should be an array whose keys are component IDs and values the corresponding component definitions.
For more details on how to specify component IDs and definitions, please refer to set().
If a component definition with the same ID already exists, it will be overwritten.
The following is an example for registering two component definitions:
[
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'sqlite:path/to/file.db',
],
'cache' => [
'class' => 'yii\caching\DbCache',
'db' => 'db',
],
]
public void setComponents ( $components ) $components array
Component definitions or instances
public function setComponents($components)
{
foreach ($components as $id => $component) {
$this->set($id, $component);
}
}
public void setContainer ( $config ) $config array
Values given in terms of name-value pairs
public function setContainer($config)
{
Yii::configure(Yii::$container, $config);
}
public function setControllerPath($path)
{
$this->_controllerPath = Yii::getAlias($path);
}
public static void setInstance ( $instance ) $instance yii\base\Module|null
The currently requested instance of this module class. If it is null
, the instance of the calling class will be removed, if any.
public static function setInstance($instance)
{
if ($instance === null) {
unset(Yii::$app->loadedModules[get_called_class()]);
} else {
Yii::$app->loadedModules[get_class($instance)] = $instance;
}
}
public function setLayoutPath($path)
{
$this->_layoutPath = Yii::getAlias($path);
}
public void setModule ( $id, $module ) $id string
Module ID.
$module yii\base\Module|array|nullThe sub-module to be added to this module. This can be one of the following:
null
: the named sub-module will be removed from this module public function setModule($id, $module)
{
if ($module === null) {
unset($this->_modules[$id]);
} else {
$this->_modules[$id] = $module;
if ($module instanceof self) {
$module->module = $this;
}
}
}
Defined in: yii\base\Module::setModules()
Registers sub-modules in the current module.
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.
If a new sub-module has the same ID as an existing one, the existing one will be overwritten silently.
The following is an example for registering two sub-modules:
[
'comment' => [
'class' => 'app\modules\comment\CommentModule',
'db' => 'db',
],
'booking' => ['class' => 'app\modules\booking\BookingModule'],
]
public void setModules ( $modules ) $modules array
Modules (id => module configuration or instances).
public function setModules($modules)
{
foreach ($modules as $id => $module) {
$this->_modules[$id] = $module;
if ($module instanceof self) {
$module->module = $this;
}
}
}
public function setRuntimePath($path)
{
$this->_runtimePath = Yii::getAlias($path);
Yii::setAlias('@runtime', $this->_runtimePath);
}
public void setTimeZone ( $value ) $value string
The time zone used by this application.
public function setTimeZone($value)
{
date_default_timezone_set($value);
}
public function setVendorPath($path)
{
$this->_vendorPath = Yii::getAlias($path);
Yii::setAlias('@vendor', $this->_vendorPath);
Yii::setAlias('@bower', $this->_vendorPath . DIRECTORY_SEPARATOR . 'bower');
Yii::setAlias('@npm', $this->_vendorPath . DIRECTORY_SEPARATOR . 'npm');
}
public void setVersion ( $version ) $version string|callable|null
The version of this module. Version can be specified as a PHP callback, which can accept module instance as an argument and should return the actual version. For example:
function (Module $module) {
}
public function setVersion($version)
{
$this->_version = $version;
}
public function setViewPath($path)
{
$this->_viewPath = Yii::getAlias($path);
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public function trigger($name, ?Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
if ($event->handled) {
return;
}
}
}
Event::trigger($this, $name, $event);
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4