Class yii\web\AssetManager
Inheritance | yii\web\AssetManager » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/web/AssetManager.php |
AssetManager manages asset bundle configuration and loading.
AssetManager is configured as an application component in yii\web\Application by default.
You can access that instance via Yii::$app->assetManager
.
You can modify its configuration by adding an array to your application config under components
as shown in the following example:
'assetManager' => [
'bundles' => [
// you can override AssetBundle configs here
],
]
For more details and usage information on AssetManager, see the guide article on assets.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$afterCopy | callable|null | A PHP callback that is called after a sub-directory or file is successfully copied. | yii\web\AssetManager |
$appendTimestamp | boolean | Whether to append a timestamp to the URL of every published asset. | yii\web\AssetManager |
$assetMap | string[] | Mapping from source asset files (keys) to target asset files (values). | yii\web\AssetManager |
$basePath | string | The root directory storing the published asset files. | yii\web\AssetManager |
$baseUrl | string | The base URL through which the published asset files can be accessed. | yii\web\AssetManager |
$beforeCopy | callable|null | A PHP callback that is called before copying each sub-directory or file. | yii\web\AssetManager |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. | yii\base\Component |
$bundles | array|false | List of asset bundle configurations. | yii\web\AssetManager |
$converter | yii\web\AssetConverterInterface | The asset converter. | yii\web\AssetManager |
$dirMode | integer | The permission to be set for newly generated asset directories. | yii\web\AssetManager |
$fileMode | integer|null | The permission to be set for newly published asset files. | yii\web\AssetManager |
$forceCopy | boolean | Whether the directory being published should be copied even if it is found in the target directory. | yii\web\AssetManager |
$hashCallback | callable|null | A callback that will be called to produce hash for asset directory generation. | yii\web\AssetManager |
$linkAssets | boolean | Whether to use symbolic link to publish asset files. | yii\web\AssetManager |
Public Methods
Method | Description | Defined 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\BaseObject |
__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 |
checkBasePathPermission() | Check whether the basePath exists and is writeable. | yii\web\AssetManager |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
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 |
getActualAssetUrl() | Returns the actual URL for the specified asset. Without parameters. | yii\web\AssetManager |
getAssetPath() | Returns the actual file path for the specified asset. | yii\web\AssetManager |
getAssetUrl() | Returns the actual URL for the specified asset. | yii\web\AssetManager |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
getBundle() | Returns the named asset bundle. | yii\web\AssetManager |
getConverter() | Returns the asset converter. | yii\web\AssetManager |
getPublishedPath() | Returns the published path of a file path. | yii\web\AssetManager |
getPublishedUrl() | Returns the URL of a published file path. | yii\web\AssetManager |
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 component. | yii\web\AssetManager |
off() | Detaches an existing event handler from this component. | yii\base\Component |
on() | Attaches an event handler to an event. | yii\base\Component |
publish() | Publishes a file or a directory. | yii\web\AssetManager |
setConverter() | Sets the asset converter. | yii\web\AssetManager |
trigger() | Triggers an event. | yii\base\Component |
Protected Methods
Method | Description | Defined By |
---|---|---|
hash() | Generate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash string. | yii\web\AssetManager |
loadBundle() | Loads asset bundle class by name. | yii\web\AssetManager |
loadDummyBundle() | Loads dummy bundle by name. | yii\web\AssetManager |
publishDirectory() | Publishes a directory. | yii\web\AssetManager |
publishFile() | Publishes a file. | yii\web\AssetManager |
resolveAsset() | yii\web\AssetManager |
Property Details
A PHP callback that is called after a sub-directory or file is successfully copied.
This option is used only when publishing a directory. The signature of the callback is the same as
for $beforeCopy.
This is passed as a parameter afterCopy
to yii\helpers\FileHelper::copyDirectory().
Whether to append a timestamp to the URL of every published asset. When this is true,
the URL of a published asset may look like /path/to/asset?v=timestamp
, where timestamp
is the
last modification time of the published asset file.
You normally would want to set this property to true when you have enabled HTTP caching for assets,
because it allows you to bust caching when the assets are updated.
Mapping from source asset files (keys) to target asset files (values).
This property is provided to support fixing incorrect asset file paths in some asset bundles.
When an asset bundle is registered with a view, each relative asset file in its css
and js arrays will be examined against this map. If any of the keys is found
to be the last part of an asset file (which is prefixed with yii\web\AssetBundle::$sourcePath if available),
the corresponding value will replace the asset and be registered with the view.
For example, an asset file my/path/to/jquery.js
matches a key jquery.js
.
Note that the target asset files should be absolute URLs, domain relative URLs (starting from '/') or paths relative to $baseUrl and $basePath.
In the following example, any assets ending with jquery.min.js
will be replaced with jquery/dist/jquery.js
which is relative to $baseUrl and $basePath.
[
'jquery.min.js' => 'jquery/dist/jquery.js',
]
You may also use aliases while specifying map value, for example:
[
'jquery.min.js' => '@web/js/jquery/jquery.js',
]
The root directory storing the published asset files.
The base URL through which the published asset files can be accessed.
A PHP callback that is called before copying each sub-directory or file. This option is used only when publishing a directory. If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
The signature of the callback should be: function ($from, $to)
, where $from
is the sub-directory or
file to be copied from, while $to
is the copy target.
This is passed as a parameter beforeCopy
to yii\helpers\FileHelper::copyDirectory().
List of asset bundle configurations. This property is provided to customize asset bundles. When a bundle is being loaded by getBundle(), if it has a corresponding configuration specified here, the configuration will be applied to the bundle.
The array keys are the asset bundle names, which typically are asset bundle class names without leading backslash. The array values are the corresponding configurations. If a value is false, it means the corresponding asset bundle is disabled and getBundle() should return null.
If this property is false, it means the whole asset bundle feature is disabled and getBundle() will always return null.
The following example shows how to disable the bootstrap css file used by Bootstrap widgets (because you want to use your own styles):
[
'yii\bootstrap\BootstrapAsset' => [
'css' => [],
],
]
The asset converter. Note that the type of this property differs in getter and setter. See getConverter() and setConverter() for details.
The permission to be set for newly generated asset directories. This value will be used by PHP chmod() function. No umask will be applied. Defaults to 0775, meaning the directory is read-writable by owner and group, but read-only for other users.
The permission to be set for newly published asset files. This value will be used by PHP chmod() function. No umask will be applied. If not set, the permission will be determined by the current environment.
Whether the directory being published should be copied even if
it is found in the target directory. This option is used only when publishing a directory.
You may want to set this to be true
during the development stage to make sure the published
directory is always up-to-date. Do not set this to true on production servers as it will
significantly degrade the performance.
A callback that will be called to produce hash for asset directory generation. The signature of the callback should be as follows:
function ($path)
where $path
is the asset path. Note that the $path
can be either directory where the asset
files reside or a single file. For a CSS file that uses relative path in url()
, the hash
implementation should use the directory path of the file instead of the file path to include
the relative asset files in the copying.
If this is not set, the asset manager will use the default CRC32 and filemtime in the hash
method.
Example of an implementation using MD4 hash:
function ($path) {
return hash('md4', $path);
}
Whether to use symbolic link to publish asset files. Defaults to false, meaning asset files are copied to $basePath. Using symbolic links has the benefit that the published assets will always be consistent with the source assets and there is no copy operation required. This is especially useful during development.
However, there are special requirements for hosting environments in order to use symbolic links. In particular, symbolic links are supported only on Linux/Unix, and Windows Vista/2008 or greater.
Moreover, some Web servers need to be properly configured so that the linked assets are accessible to Web users. For example, for Apache Web server, the following configuration directive should be added for the Web folder:
Options FollowSymLinks
Method Details
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 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 |
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 void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Defined in: yii\base\BaseObject::__construct()
Constructor.
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call init().
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
public void __construct ( $config = [] ) | ||
$config | array |
Name-value pairs that will be used to initialize the object properties |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
Defined in: yii\base\Component::__get()
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. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
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)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
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. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$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:
- 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)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$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\Component::attachBehavior()
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 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
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 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
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 array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Defined in: yii\base\Component::canGetProperty()
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 |
---|
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:
- 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 |
---|
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;
}
Check whether the basePath exists and is writeable.
public void checkBasePathPermission ( ) |
public function checkBasePathPermission()
{
// if the check is been done already, skip further checks
if ($this->_isBasePathPermissionChecked) {
return;
}
if (!is_dir($this->basePath)) {
throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
}
if (!is_writable($this->basePath)) {
throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
}
$this->_isBasePathPermissionChecked = true;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
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;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Returns the actual URL for the specified asset. Without parameters.
The actual URL is obtained by prepending either yii\web\AssetBundle::$baseUrl or yii\web\AssetManager::$baseUrl to the given asset path.
public string getActualAssetUrl ( $bundle, $asset ) | ||
$bundle | yii\web\AssetBundle |
The asset bundle which the asset file belongs to |
$asset | string |
The asset path. This should be one of the assets listed in yii\web\AssetBundle::$js or yii\web\AssetBundle::$css. |
return | string |
The actual URL for the specified asset. |
---|
public function getActualAssetUrl($bundle, $asset)
{
if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
if (strncmp($actualAsset, '@web/', 5) === 0) {
$asset = substr($actualAsset, 5);
$baseUrl = Yii::getAlias('@web');
} else {
$asset = Yii::getAlias($actualAsset);
$baseUrl = $this->baseUrl;
}
} else {
$baseUrl = $bundle->baseUrl;
}
if (!Url::isRelative($asset) || strncmp($asset, '/', 1) === 0) {
return $asset;
}
return "$baseUrl/$asset";
}
Returns the actual file path for the specified asset.
public string|false getAssetPath ( $bundle, $asset ) | ||
$bundle | yii\web\AssetBundle |
The asset bundle which the asset file belongs to |
$asset | string |
The asset path. This should be one of the assets listed in yii\web\AssetBundle::$js or yii\web\AssetBundle::$css. |
return | string|false |
The actual file path, or |
---|
public function getAssetPath($bundle, $asset)
{
if (($actualAsset = $this->resolveAsset($bundle, $asset)) !== false) {
return Url::isRelative($actualAsset) ? $this->basePath . '/' . $actualAsset : false;
}
return Url::isRelative($asset) ? $bundle->basePath . '/' . $asset : false;
}
Returns the actual URL for the specified asset.
The actual URL is obtained by prepending either yii\web\AssetBundle::$baseUrl or yii\web\AssetManager::$baseUrl to the given asset path.
public string getAssetUrl ( $bundle, $asset, $appendTimestamp = null ) | ||
$bundle | yii\web\AssetBundle |
The asset bundle which the asset file belongs to |
$asset | string |
The asset path. This should be one of the assets listed in yii\web\AssetBundle::$js or yii\web\AssetBundle::$css. |
$appendTimestamp | boolean|null |
Whether to append timestamp to the URL. |
return | string |
The actual URL for the specified asset. |
---|
public function getAssetUrl($bundle, $asset, $appendTimestamp = null)
{
$assetUrl = $this->getActualAssetUrl($bundle, $asset);
$assetPath = $this->getAssetPath($bundle, $asset);
$withTimestamp = $this->appendTimestamp;
if ($appendTimestamp !== null) {
$withTimestamp = $appendTimestamp;
}
if ($withTimestamp && $assetPath && ($timestamp = @filemtime($assetPath)) > 0) {
return "$assetUrl?v=$timestamp";
}
return $assetUrl;
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
Returns the named asset bundle.
This method will first look for the bundle in $bundles. If not found,
it will treat $name
as the class of the asset bundle and create a new instance of it.
public yii\web\AssetBundle getBundle ( $name, $publish = true ) | ||
$name | string |
The class name of the asset bundle (without the leading backslash) |
$publish | boolean |
Whether to publish the asset files in the asset bundle before it is returned.
If you set this false, you must manually call |
return | yii\web\AssetBundle |
The asset bundle instance |
---|---|---|
throws | yii\base\InvalidConfigException |
if $name does not refer to a valid asset bundle |
public function getBundle($name, $publish = true)
{
if ($this->bundles === false) {
return $this->loadDummyBundle($name);
} elseif (!isset($this->bundles[$name])) {
return $this->bundles[$name] = $this->loadBundle($name, [], $publish);
} elseif ($this->bundles[$name] instanceof AssetBundle) {
return $this->bundles[$name];
} elseif (is_array($this->bundles[$name])) {
return $this->bundles[$name] = $this->loadBundle($name, $this->bundles[$name], $publish);
} elseif ($this->bundles[$name] === false) {
return $this->loadDummyBundle($name);
}
throw new InvalidConfigException("Invalid asset bundle configuration: $name");
}
Returns the asset converter.
public yii\web\AssetConverterInterface getConverter ( ) | ||
return | yii\web\AssetConverterInterface |
The asset converter. |
---|
public function getConverter()
{
if ($this->_converter === null) {
$this->_converter = Yii::createObject(AssetConverter::className());
} elseif (is_array($this->_converter) || is_string($this->_converter)) {
if (is_array($this->_converter) && !isset($this->_converter['class'])) {
$this->_converter['class'] = AssetConverter::className();
}
$this->_converter = Yii::createObject($this->_converter);
}
return $this->_converter;
}
Returns the published path of a file path.
This method does not perform any publishing. It merely tells you if the file or directory is published, where it will go.
public string|false getPublishedPath ( $path ) | ||
$path | string |
Directory or file path being published |
return | string|false |
String the published file path. False if the file or directory does not exist |
---|
public function getPublishedPath($path)
{
$path = Yii::getAlias($path);
if (isset($this->_published[$path])) {
return $this->_published[$path][0];
}
if (is_string($path) && ($path = realpath($path)) !== false) {
return $this->basePath . DIRECTORY_SEPARATOR . $this->hash($path) . (is_file($path) ? DIRECTORY_SEPARATOR . basename($path) : '');
}
return false;
}
Returns the URL of a published file path.
This method does not perform any publishing. It merely tells you if the file path is published, what the URL will be to access it.
public string|false getPublishedUrl ( $path ) | ||
$path | string |
Directory or file path being published |
return | string|false |
String the published URL for the file or directory. False if the file or directory does not exist. |
---|
public function getPublishedUrl($path)
{
$path = Yii::getAlias($path);
if (isset($this->_published[$path])) {
return $this->_published[$path][1];
}
if (is_string($path) && ($path = realpath($path)) !== false) {
return $this->baseUrl . '/' . $this->hash($path) . (is_file($path) ? '/' . basename($path) : '');
}
return false;
}
Defined in: yii\base\Component::hasEventHandlers()
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. |
---|
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:
- 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 |
---|
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\Component::hasProperty()
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 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Generate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash string.
protected string hash ( $path ) | ||
$path | string |
String to be hashed. |
return | string |
Hashed string. |
---|
protected function hash($path)
{
if (is_callable($this->hashCallback)) {
return call_user_func($this->hashCallback, $path);
}
$path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
return sprintf('%x', crc32($path . Yii::getVersion() . '|' . $this->linkAssets));
}
Initializes the component.
public void init ( ) | ||
throws | yii\base\InvalidConfigException |
if $basePath does not exist. |
---|
public function init()
{
parent::init();
$this->basePath = Yii::getAlias($this->basePath);
$this->basePath = realpath($this->basePath);
$this->baseUrl = rtrim(Yii::getAlias($this->baseUrl), '/');
}
Loads asset bundle class by name.
protected yii\web\AssetBundle loadBundle ( $name, $config = [], $publish = true ) | ||
$name | string |
Bundle name |
$config | array |
Bundle object configuration |
$publish | boolean |
If bundle should be published |
throws | yii\base\InvalidConfigException |
if configuration isn't valid |
---|
protected function loadBundle($name, $config = [], $publish = true)
{
if (!isset($config['class'])) {
$config['class'] = $name;
}
/* @var $bundle AssetBundle */
$bundle = Yii::createObject($config);
if ($publish) {
$bundle->publish($this);
}
return $bundle;
}
Loads dummy bundle by name.
protected yii\web\AssetBundle loadDummyBundle ( $name ) | ||
$name | string |
protected function loadDummyBundle($name)
{
if (!isset($this->_dummyBundles[$name])) {
$bundle = Yii::createObject(['class' => $name]);
$bundle->sourcePath = null;
$bundle->js = [];
$bundle->css = [];
$this->_dummyBundles[$name] = $bundle;
}
return $this->_dummyBundles[$name];
}
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 | string |
Event name |
$handler | callable|null |
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 |
---|
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;
// plain event names
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;
}
}
// wildcard event names
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]);
// remove empty wildcards to save future redundant regex checks:
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) { ... } // 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.
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 | 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. |
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]);
}
}
Publishes a file or a directory.
This method will copy the specified file or directory to $basePath so that it can be accessed via the Web server.
If the asset is a file, its file modification time will be checked to avoid unnecessary file copying.
If the asset is a directory, all files and subdirectories under it will be published recursively. Note, in case $forceCopy is false the method only checks the existence of the target directory to avoid repetitive copying (which is very expensive).
By default, when publishing a directory, subdirectories and files whose name starts with a dot "."
will NOT be published. If you want to change this behavior, you may specify the "beforeCopy" option
as explained in the $options
parameter.
Note: On rare scenario, a race condition can develop that will lead to a one-time-manifestation of a non-critical problem in the creation of the directory that holds the published assets. This problem can be avoided altogether by 'requesting' in advance all the resources that are supposed to trigger a 'publish()' call, and doing that in the application deployment phase, before system goes live. See more in the following discussion: https://code.google.com/archive/p/yii/issues/2579
public array publish ( $path, $options = [] ) | ||
$path | string |
The asset (file or directory) to be published |
$options | array |
The options to be applied when publishing a directory. The following options are supported:
|
return | array |
The path (directory or file path) and the URL that the asset is published as. |
---|---|---|
throws | yii\base\InvalidArgumentException |
if the asset to be published does not exist. |
throws | yii\base\InvalidConfigException |
if the target directory $basePath is not writeable. |
public function publish($path, $options = [])
{
$path = Yii::getAlias($path);
if (isset($this->_published[$path])) {
return $this->_published[$path];
}
if (!is_string($path) || ($src = realpath($path)) === false) {
throw new InvalidArgumentException("The file or directory to be published does not exist: $path");
}
if (!is_readable($path)) {
throw new InvalidArgumentException("The file or directory to be published is not readable: $path");
}
if (is_file($src)) {
return $this->_published[$path] = $this->publishFile($src);
}
return $this->_published[$path] = $this->publishDirectory($src, $options);
}
Publishes a directory.
protected string[] publishDirectory ( $src, $options ) | ||
$src | string |
The asset directory to be published |
$options | array |
The options to be applied when publishing a directory. The following options are supported:
|
return | string[] |
The path directory and the URL that the asset is published as. |
---|---|---|
throws | yii\base\InvalidArgumentException |
if the asset to be published does not exist. |
protected function publishDirectory($src, $options)
{
$this->checkBasePathPermission();
$dir = $this->hash($src);
$dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
if ($this->linkAssets) {
if (!is_dir($dstDir)) {
FileHelper::createDirectory(dirname($dstDir), $this->dirMode, true);
try { // fix #6226 symlinking multi threaded
symlink($src, $dstDir);
} catch (\Exception $e) {
if (!is_dir($dstDir)) {
throw $e;
}
}
}
} elseif (!empty($options['forceCopy']) || ($this->forceCopy && !isset($options['forceCopy'])) || !is_dir($dstDir)) {
$opts = array_merge(
$options,
[
'dirMode' => $this->dirMode,
'fileMode' => $this->fileMode,
'copyEmptyDirectories' => false,
]
);
if (!isset($opts['beforeCopy'])) {
if ($this->beforeCopy !== null) {
$opts['beforeCopy'] = $this->beforeCopy;
} else {
$opts['beforeCopy'] = function ($from, $to) {
return strncmp(basename($from), '.', 1) !== 0;
};
}
}
if (!isset($opts['afterCopy']) && $this->afterCopy !== null) {
$opts['afterCopy'] = $this->afterCopy;
}
FileHelper::copyDirectory($src, $dstDir, $opts);
}
return [$dstDir, $this->baseUrl . '/' . $dir];
}
Publishes a file.
protected string[] publishFile ( $src ) | ||
$src | string |
The asset file to be published |
return | string[] |
The path and the URL that the asset is published as. |
---|---|---|
throws | yii\base\InvalidArgumentException |
if the asset to be published does not exist. |
protected function publishFile($src)
{
$this->checkBasePathPermission();
$dir = $this->hash($src);
$fileName = basename($src);
$dstDir = $this->basePath . DIRECTORY_SEPARATOR . $dir;
$dstFile = $dstDir . DIRECTORY_SEPARATOR . $fileName;
if (!is_dir($dstDir)) {
FileHelper::createDirectory($dstDir, $this->dirMode, true);
}
if ($this->linkAssets) {
if (!is_file($dstFile)) {
try { // fix #6226 symlinking multi threaded
symlink($src, $dstFile);
} catch (\Exception $e) {
if (!is_file($dstFile)) {
throw $e;
}
}
}
} elseif (@filemtime($dstFile) < @filemtime($src)) {
copy($src, $dstFile);
if ($this->fileMode !== null) {
@chmod($dstFile, $this->fileMode);
}
}
if ($this->appendTimestamp && ($timestamp = @filemtime($dstFile)) > 0) {
$fileName = $fileName . "?v=$timestamp";
}
return [$dstFile, $this->baseUrl . "/$dir/$fileName"];
}
protected string|false resolveAsset ( $bundle, $asset ) | ||
$bundle | yii\web\AssetBundle | |
$asset | string |
protected function resolveAsset($bundle, $asset)
{
if (isset($this->assetMap[$asset])) {
return $this->assetMap[$asset];
}
if ($bundle->sourcePath !== null && Url::isRelative($asset)) {
$asset = $bundle->sourcePath . '/' . $asset;
}
$n = mb_strlen($asset, Yii::$app->charset);
foreach ($this->assetMap as $from => $to) {
$n2 = mb_strlen($from, Yii::$app->charset);
if ($n2 <= $n && substr_compare($asset, $from, $n - $n2, $n2) === 0) {
return $to;
}
}
return false;
}
Sets the asset converter.
public void setConverter ( $value ) | ||
$value | array|yii\web\AssetConverterInterface |
The asset converter. This can be either an object implementing the yii\web\AssetConverterInterface, or a configuration array that can be used to create the asset converter object. |
public function setConverter($value)
{
$this->_converter = $value;
}
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 void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
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);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}