Class yii\web\AssetManager

Inheritanceyii\web\AssetManager » yii\base\Component » yii\base\BaseObject
Implementsyii\base\Configurable
Available since version2.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

Hide inherited properties

PropertyTypeDescriptionDefined By
$afterCopy callback 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 array 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 callback 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. This property is read-only. yii\base\Component
$bundles array|boolean List of asset bundle configurations. yii\web\AssetManager
$converter yii\web\AssetConverterInterface The asset converter. Note that the type of this property differs in getter and setter. See getConverter() and setConverter() for details. yii\web\AssetManager
$dirMode integer The permission to be set for newly generated asset directories. yii\web\AssetManager
$fileMode integer 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 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

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\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

Hide inherited methods

MethodDescriptionDefined 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

$afterCopy public property

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().

public callback $afterCopy null
$appendTimestamp public property (available since version 2.0.3)

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.

public boolean $appendTimestamp false
$assetMap public property

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',
]
public array $assetMap = []
$basePath public property

The root directory storing the published asset files.

public string $basePath '@webroot/assets'
$baseUrl public property

The base URL through which the published asset files can be accessed.

public string $baseUrl '@web/assets'
$beforeCopy public property

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().

public callback $beforeCopy null
$bundles public property

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' => [],
    ],
]
public array|boolean $bundles = []
$converter public property

The asset converter. Note that the type of this property differs in getter and setter. See getConverter() and setConverter() for details.

$dirMode public property

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.

public integer $dirMode 0775
$fileMode public property

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.

public integer $fileMode null
$forceCopy public property

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.

public boolean $forceCopy false
$hashCallback public property (available since version 2.0.6)

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);
}
public callable $hashCallback null
$linkAssets public property

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
public boolean $linkAssets false

Method Details

checkBasePathPermission() public method (available since version 2.0.40)

Check whether the basePath exists and is writeable.

public void checkBasePathPermission ( )
getActualAssetUrl() public method (available since version 2.0.39)

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.

getAssetPath() public method

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 false if the asset is specified as an absolute URL

getAssetUrl() public method

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.

getBundle() public method

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 AssetBundle::publish() to publish the asset files.

return yii\web\AssetBundle

The asset bundle instance

throws yii\base\InvalidConfigException

if $name does not refer to a valid asset bundle

getConverter() public method

Returns the asset converter.

public yii\web\AssetConverterInterface getConverter ( )
return yii\web\AssetConverterInterface

The asset converter.

getPublishedPath() public method

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

getPublishedUrl() public method

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.

hash() protected method

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.

init() public method

Initializes the component.

public void init ( )
throws yii\base\InvalidConfigException

if $basePath does not exist.

loadBundle() protected method

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

loadDummyBundle() protected method

Loads dummy bundle by name.

protected yii\web\AssetBundle loadDummyBundle ( $name )
$name string
publish() public method

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: http://code.google.com/p/yii/issues/detail?id=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:

  • only: array, list of patterns that the file paths should match if they want to be copied.
  • except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  • caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  • beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. This overrides $beforeCopy if set.
  • afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied. This overrides $afterCopy if set.
  • forceCopy: boolean, 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. This overrides $forceCopy if set.
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.

publishDirectory() protected method

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:

  • only: array, list of patterns that the file paths should match if they want to be copied.
  • except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
  • caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  • beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. This overrides $beforeCopy if set.
  • afterCopy: callback, a PHP callback that is called after a sub-directory or file is successfully copied. This overrides $afterCopy if set.
  • forceCopy: boolean, 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. This overrides $forceCopy if set.
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.

publishFile() protected method

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.

resolveAsset() protected method

protected string|boolean resolveAsset ( $bundle, $asset )
$bundle yii\web\AssetBundle
$asset string
setConverter() public method

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.