Class yii\base\Component

Inheritanceyii\base\Component » yii\base\Object
Implementsyii\base\Configurable
Subclassesyii\apidoc\commands\ApiController, yii\apidoc\commands\GuideController, yii\apidoc\components\BaseController, yii\apidoc\models\Context, yii\apidoc\renderers\ApiRenderer, yii\apidoc\renderers\BaseRenderer, yii\apidoc\renderers\GuideRenderer, yii\apidoc\templates\bootstrap\ApiRenderer, yii\apidoc\templates\bootstrap\GuideRenderer, yii\apidoc\templates\bootstrap\SideNavWidget, yii\apidoc\templates\html\ApiRenderer, yii\apidoc\templates\html\GuideRenderer, yii\apidoc\templates\json\ApiRenderer, yii\apidoc\templates\online\ApiRenderer, yii\apidoc\templates\pdf\GuideRenderer, yii\authclient\AuthAction, yii\authclient\BaseClient, yii\authclient\BaseOAuth, yii\authclient\Collection, yii\authclient\OAuth1, yii\authclient\OAuth2, yii\authclient\OpenId, yii\authclient\SessionStateStorage, yii\authclient\clients\Facebook, yii\authclient\clients\GitHub, yii\authclient\clients\Google, yii\authclient\clients\GoogleHybrid, yii\authclient\clients\LinkedIn, yii\authclient\clients\Live, yii\authclient\clients\Twitter, yii\authclient\clients\VKontakte, yii\authclient\clients\Yandex, yii\authclient\widgets\AuthChoice, yii\authclient\widgets\AuthChoiceItem, yii\authclient\widgets\GooglePlusButton, yii\base\Action, yii\base\Application, yii\base\Controller, yii\base\DynamicModel, yii\base\ErrorHandler, yii\base\InlineAction, yii\base\Model, yii\base\Module, yii\base\Request, yii\base\Response, yii\base\Security, yii\base\Theme, yii\base\View, yii\base\ViewRenderer, yii\base\Widget, yii\bootstrap\ActiveField, yii\bootstrap\ActiveForm, yii\bootstrap\Alert, yii\bootstrap\Button, yii\bootstrap\ButtonDropdown, yii\bootstrap\ButtonGroup, yii\bootstrap\Carousel, yii\bootstrap\Collapse, yii\bootstrap\Dropdown, yii\bootstrap\InputWidget, yii\bootstrap\Modal, yii\bootstrap\Nav, yii\bootstrap\NavBar, yii\bootstrap\Progress, yii\bootstrap\Tabs, yii\bootstrap\ToggleButtonGroup, yii\bootstrap\Widget, yii\caching\ApcCache, yii\caching\ArrayCache, yii\caching\Cache, yii\caching\DbCache, yii\caching\DummyCache, yii\caching\FileCache, yii\caching\MemCache, yii\caching\WinCache, yii\caching\XCache, yii\caching\ZendDataCache, yii\captcha\Captcha, yii\captcha\CaptchaAction, yii\captcha\CaptchaValidator, yii\codeception\BasePage, yii\console\Application, yii\console\Controller, yii\console\ErrorHandler, yii\console\Request, yii\console\Response, yii\console\controllers\AssetController, yii\console\controllers\BaseMigrateController, yii\console\controllers\CacheController, yii\console\controllers\FixtureController, yii\console\controllers\HelpController, yii\console\controllers\MessageController, yii\console\controllers\MigrateController, yii\console\controllers\ServeController, yii\data\ActiveDataProvider, yii\data\ArrayDataProvider, yii\data\BaseDataProvider, yii\data\SqlDataProvider, yii\db\ActiveQuery, yii\db\ActiveRecord, yii\db\BaseActiveRecord, yii\db\Command, yii\db\Connection, yii\db\Migration, yii\db\Query, yii\debug\LogTarget, yii\debug\Module, yii\debug\Panel, yii\debug\actions\db\ExplainAction, yii\debug\components\search\Filter, yii\debug\components\search\matchers\Base, yii\debug\components\search\matchers\GreaterThan, yii\debug\components\search\matchers\GreaterThanOrEqual, yii\debug\components\search\matchers\LowerThan, yii\debug\components\search\matchers\SameAs, yii\debug\controllers\DefaultController, yii\debug\models\Router, yii\debug\models\search\Base, yii\debug\models\search\Db, yii\debug\models\search\Debug, yii\debug\models\search\Log, yii\debug\models\search\Mail, yii\debug\models\search\Profile, yii\debug\models\timeline\DataProvider, yii\debug\models\timeline\Search, yii\debug\panels\AssetPanel, yii\debug\panels\ConfigPanel, yii\debug\panels\DbPanel, yii\debug\panels\LogPanel, yii\debug\panels\MailPanel, yii\debug\panels\ProfilingPanel, yii\debug\panels\RequestPanel, yii\debug\panels\RouterPanel, yii\debug\panels\TimelinePanel, yii\debug\panels\UserPanel, yii\di\Container, yii\di\ServiceLocator, yii\elasticsearch\ActiveDataProvider, yii\elasticsearch\ActiveFixture, yii\elasticsearch\ActiveQuery, yii\elasticsearch\ActiveRecord, yii\elasticsearch\BulkCommand, yii\elasticsearch\Command, yii\elasticsearch\Connection, yii\elasticsearch\DebugAction, yii\elasticsearch\DebugPanel, yii\elasticsearch\ElasticsearchTarget, yii\elasticsearch\Query, yii\faker\FixtureController, yii\filters\AccessRule, yii\gii\Generator, yii\gii\Module, yii\gii\components\ActiveField, yii\gii\console\GenerateAction, yii\gii\console\GenerateController, yii\gii\controllers\DefaultController, yii\gii\generators\controller\Generator, yii\gii\generators\crud\Generator, yii\gii\generators\extension\Generator, yii\gii\generators\form\Generator, yii\gii\generators\model\Generator, yii\gii\generators\module\Generator, yii\grid\GridView, yii\httpclient\Client, yii\httpclient\CurlTransport, yii\httpclient\Message, yii\httpclient\Request, yii\httpclient\Response, yii\httpclient\StreamTransport, yii\httpclient\Transport, yii\httpclient\debug\HttpClientPanel, yii\httpclient\debug\RequestExecuteAction, yii\httpclient\debug\SearchModel, yii\i18n\DbMessageSource, yii\i18n\Formatter, yii\i18n\GettextFile, yii\i18n\GettextMessageSource, yii\i18n\GettextMoFile, yii\i18n\GettextPoFile, yii\i18n\I18N, yii\i18n\MessageFormatter, yii\i18n\MessageSource, yii\i18n\PhpMessageSource, yii\jui\Accordion, yii\jui\AutoComplete, yii\jui\DatePicker, yii\jui\Dialog, yii\jui\Draggable, yii\jui\Droppable, yii\jui\InputWidget, yii\jui\Menu, yii\jui\ProgressBar, yii\jui\Resizable, yii\jui\Selectable, yii\jui\Slider, yii\jui\SliderInput, yii\jui\Sortable, yii\jui\Spinner, yii\jui\Tabs, yii\jui\Widget, yii\log\DbTarget, yii\log\Dispatcher, yii\log\EmailTarget, yii\log\FileTarget, yii\log\Logger, yii\log\SyslogTarget, yii\log\Target, yii\mail\BaseMailer, yii\mongodb\ActiveFixture, yii\mongodb\ActiveQuery, yii\mongodb\ActiveRecord, yii\mongodb\Cache, yii\mongodb\Connection, yii\mongodb\Migration, yii\mongodb\Query, yii\mongodb\Session, yii\mongodb\console\controllers\MigrateController, yii\mongodb\debug\ExplainAction, yii\mongodb\debug\MongoDbPanel, yii\mongodb\file\ActiveQuery, yii\mongodb\file\ActiveRecord, yii\mongodb\file\Query, yii\mongodb\gii\model\Generator, yii\mongodb\i18n\MongoDbMessageSource, yii\mongodb\log\MongoDbTarget, yii\mongodb\rbac\MongoDbManager, yii\mongodb\validators\MongoDateValidator, yii\mongodb\validators\MongoIdValidator, yii\mutex\DbMutex, yii\mutex\FileMutex, yii\mutex\Mutex, yii\mutex\MysqlMutex, yii\mutex\OracleMutex, yii\mutex\PgsqlMutex, yii\rbac\BaseManager, yii\rbac\DbManager, yii\rbac\PhpManager, yii\redis\ActiveQuery, yii\redis\ActiveRecord, yii\redis\Cache, yii\redis\Connection, yii\redis\Mutex, yii\redis\Session, yii\rest\Action, yii\rest\ActiveController, yii\rest\Controller, yii\rest\CreateAction, yii\rest\DeleteAction, yii\rest\IndexAction, yii\rest\OptionsAction, yii\rest\Serializer, yii\rest\UpdateAction, yii\rest\ViewAction, yii\shell\ShellController, yii\smarty\ViewRenderer, yii\sphinx\ActiveDataProvider, yii\sphinx\ActiveFixture, yii\sphinx\ActiveQuery, yii\sphinx\ActiveRecord, yii\sphinx\Command, yii\sphinx\Connection, yii\sphinx\Query, yii\sphinx\gii\model\Generator, yii\swiftmailer\Mailer, yii\test\ActiveFixture, yii\test\ArrayFixture, yii\test\BaseActiveFixture, yii\test\DbFixture, yii\test\Fixture, yii\test\InitDbFixture, yii\twig\ViewRenderer, yii\validators\BooleanValidator, yii\validators\CompareValidator, yii\validators\DateValidator, yii\validators\DefaultValueValidator, yii\validators\EachValidator, yii\validators\EmailValidator, yii\validators\ExistValidator, yii\validators\FileValidator, yii\validators\FilterValidator, yii\validators\ImageValidator, yii\validators\InlineValidator, yii\validators\IpValidator, yii\validators\NumberValidator, yii\validators\RangeValidator, yii\validators\RegularExpressionValidator, yii\validators\RequiredValidator, yii\validators\SafeValidator, yii\validators\StringValidator, yii\validators\UniqueValidator, yii\validators\UrlValidator, yii\validators\Validator, yii\web\Application, yii\web\AssetConverter, yii\web\AssetManager, yii\web\CacheSession, yii\web\Controller, yii\web\DbSession, yii\web\ErrorAction, yii\web\ErrorHandler, yii\web\HtmlResponseFormatter, yii\web\JsonResponseFormatter, yii\web\MultiFieldSession, yii\web\Request, yii\web\Response, yii\web\Session, yii\web\UrlManager, yii\web\User, yii\web\View, yii\web\ViewAction, yii\web\XmlResponseFormatter, yii\widgets\ActiveField, yii\widgets\ActiveForm, yii\widgets\BaseListView, yii\widgets\Block, yii\widgets\Breadcrumbs, yii\widgets\ContentDecorator, yii\widgets\DetailView, yii\widgets\FragmentCache, yii\widgets\InputWidget, yii\widgets\LinkPager, yii\widgets\LinkSorter, yii\widgets\ListView, yii\widgets\MaskedInput, yii\widgets\Menu, yii\widgets\Pjax, yii\widgets\Spaceless
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/base/Component.php

Component is the base class that implements the property, event and behavior features.

Component provides the event and behavior features, in addition to the property feature which is implemented in its parent class Object.

Event is a way to "inject" custom code into existing code at certain places. For example, a comment object can trigger an "add" event when the user adds a comment. We can write custom code and attach it to this event so that when the event is triggered (i.e. comment will be added), our custom code will be executed.

An event is identified by a name that should be unique within the class it is defined at. Event names are case-sensitive.

One or multiple PHP callbacks, called event handlers, can be attached to an event. You can call trigger() to raise an event. When an event is raised, the event handlers will be invoked automatically in the order they were attached.

To attach an event handler to an event, call on():

$post->on('update', function ($event) {
    // send email notification
});

In the above, an anonymous function is attached to the "update" event of the post. You may attach the following types of event handlers:

  • anonymous function: function ($event) { ... }
  • object method: [$object, 'handleAdd']
  • static class method: ['Page', 'handleAdd']
  • global function: 'handleAdd'

The signature of an event handler should be like the following:

function foo($event)

where $event is an yii\base\Event object which includes parameters associated with the event.

You can also attach a handler to an event when configuring a component with a configuration array. The syntax is like the following:

[
    'on add' => function ($event) { ... }
]

where on add stands for attaching an event to the add event.

Sometimes, you may want to associate extra data with an event handler when you attach it to an event and then access it when the handler is invoked. You may do so by

$post->on('update', function ($event) {
    // the data can be accessed via $event->data
}, $data);

A behavior is an instance of yii\base\Behavior or its child class. A component can be attached with one or multiple behaviors. When a behavior is attached to a component, its public properties and methods can be accessed via the component directly, as if the component owns those properties and methods.

To attach a behavior to a component, declare it in behaviors(), or explicitly call attachBehavior(). Behaviors declared in behaviors() are automatically attached to the corresponding component.

One can also attach a behavior to a component when configuring it with a configuration array. The syntax is like the following:

[
    'as tree' => [
        'class' => 'Tree',
    ],
]

where as tree stands for attaching a behavior named tree, and the array will be passed to Yii::createObject() to create the behavior object.

For more details and usage information on Component, see the guide article on components.

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
$behaviors yii\base\Behavior[] List of behaviors attached to this component yii\base\Component

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. yii\base\Object
__get() Returns the value of a component property. yii\base\Component
__isset() Checks if a property is set, i.e. defined and not null. yii\base\Component
__set() Sets the value of a component property. yii\base\Component
__unset() Sets a component property to be null. yii\base\Component
attachBehavior() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
behaviors() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\base\Component
canSetProperty() Returns a value indicating whether a property can be set. yii\base\Component
className() Returns the fully qualified name of this class. yii\base\Object
detachBehavior() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yii\base\Component
getBehavior() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\base\Object
off() Detaches an existing event handler from this component. yii\base\Component
on() Attaches an event handler to an event. yii\base\Component
trigger() Triggers an event. yii\base\Component

Property Details

$behaviors public read-only property

List of behaviors attached to this component

Method Details

__call() public method

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 mixed __call ( $name, $params )
$name string

The method name

$params array

Method parameters

return mixed

The method return value

throws yii\base\UnknownMethodException

when calling unknown method

__clone() public method

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 void __clone ( )
__get() public method

Returns the value of a component property.

This method will check in the following order and act accordingly:

  • a property defined by a getter: return the getter result
  • a property of a behavior: return the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

See also __set().

public mixed __get ( $name )
$name string

The property name

return mixed

The property value or the value of a behavior's property

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is write-only.

__isset() public method

Checks if a property is set, i.e. defined and not null.

This method will check in the following order and act accordingly:

  • a property defined by a setter: return whether the property is set
  • a property of a behavior: return whether the property is set
  • return false for non existing properties

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

See also http://php.net/manual/en/function.isset.php.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the named property is set

__set() public method

Sets the value of a component property.

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value
  • an event in the format of "on xyz": attach the handler to the event "xyz"
  • a behavior in the format of "as xyz": attach the behavior named as "xyz"
  • a property of a behavior: set the behavior property value

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 void __set ( $name, $value )
$name string

The property name or the event name

$value mixed

The property value

throws yii\base\UnknownPropertyException

if the property is not defined

throws yii\base\InvalidCallException

if the property is read-only.

__unset() public method

Sets a component property to be null.

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value to be null
  • a property of a behavior: set the property value to be null

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 http://php.net/manual/en/function.unset.php.

public void __unset ( $name )
$name string

The property name

throws yii\base\InvalidCallException

if the property is read only.

attachBehavior() public method

Attaches a behavior to this component.

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.

See also detachBehavior().

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

The name of the behavior.

$behavior string|array|yii\base\Behavior

The behavior configuration. This can be one of the following:

return yii\base\Behavior

The behavior object

attachBehaviors() public method

Attaches a list of behaviors to the component.

Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.

See also attachBehavior().

public void attachBehaviors ( $behaviors )
$behaviors array

List of behaviors to be attached to the component

behaviors() public method

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 array behaviors ( )
return array

The behavior configurations.

canGetProperty() public method

Returns a value indicating whether a property can be read.

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).

See also canSetProperty().

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be read

canSetProperty() public method

Returns a value indicating whether a property can be set.

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).

See also canGetProperty().

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be written

detachBehavior() public method

Detaches a behavior from the component.

The behavior's yii\base\Behavior::detach() method will be invoked.

public null|yii\base\Behavior detachBehavior ( $name )
$name string

The behavior's name.

return null|yii\base\Behavior

The detached behavior. Null if the behavior does not exist.

detachBehaviors() public method

Detaches all behaviors from the component.

public void detachBehaviors ( )
ensureBehaviors() public method

Makes sure that the behaviors declared in behaviors() are attached to this component.

public void ensureBehaviors ( )
getBehavior() public method

Returns the named behavior object.

public null|yii\base\Behavior getBehavior ( $name )
$name string

The behavior name

return null|yii\base\Behavior

The behavior object, or null if the behavior does not exist

getBehaviors() public method

Returns all behaviors attached to this component.

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

List of behaviors attached to this component

hasEventHandlers() public method

Returns a value indicating whether there is any handler attached to the named event.

public boolean hasEventHandlers ( $name )
$name string

The event name

return boolean

Whether there is any handler attached to the event.

hasMethod() public method

Returns a value indicating whether a method is defined.

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

The property name

$checkBehaviors boolean

Whether to treat behaviors' methods as methods of this component

return boolean

Whether the method is defined

hasProperty() public method

Returns a value indicating whether a property is defined for this component.

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).

See also:

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property is defined

off() public method

Detaches an existing event handler from this component.

This method is the opposite of on().

See also on().

public boolean off ( $name, $handler null )
$name string

Event name

$handler callable

The event handler to be removed. If it is null, all handlers attached to the named event will be removed.

return boolean

If a handler is found and detached

on() public method

Attaches an event handler to an event.

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function 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.

See also off().

public void on ( $name, $handler, $data null, $append true )
$name string

The event name

$handler callable

The event handler

$data mixed

The 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 boolean

Whether 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.

trigger() public method

Triggers an event.

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

public void trigger ( $name, yii\base\Event $event null )
$name string

The event name

$event yii\base\Event

The event parameter. If not set, a default yii\base\Event object will be created.