AssetManager
API reference › yii › web › AssetManager
AssetManager manages asset bundle configuration and loading.
AssetManager is configured as an application component in 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.
Properties
Section titled “Properties”| Property | Type | Description | Defined by |
|---|---|---|---|
$afterCopy | callable| | A PHP callback that is called after a sub-directory or file is successfully copied. Default: null. | AssetManager |
$appendTimestamp | bool | Whether to append a timestamp to the URL of every published asset. Default: false. Available since 2.0.3. | AssetManager |
$assetMap | string[] | Mapping from source asset files (keys) to target asset files (values). Default: []. | AssetManager |
$basePath | string | The root directory storing the published asset files. Default: '@webroot/assets'. | AssetManager |
$baseUrl | string | The base URL through which the published asset files can be accessed. Default: '@web/assets'. | AssetManager |
$beforeCopy | callable| | A PHP callback that is called before copying each sub-directory or file. Default: null. | AssetManager |
$behaviors read-only | array<yii\<static>> | List of behaviors attached to this component. | yii\ |
$bundles | array| | List of asset bundle configurations. Default: []. | AssetManager |
$converter | array|AssetConverterInterface | The asset converter. | AssetManager |
$dirMode | int | The permission to be set for newly generated asset directories. Default: 0775. | AssetManager |
$fileMode | int| | The permission to be set for newly published asset files. Default: null. | AssetManager |
$forceCopy | bool | Whether the directory being published should be copied even if it is found in the target directory. Default: false. | AssetManager |
$hashCallback | callable| | A callback that will be called to produce hash for asset directory generation. Default: null. Available since 2.0.6. | AssetManager |
$linkAssets | bool | Whether to use symbolic link to publish asset files. Default: false. | AssetManager |
Methods
Section titled “Methods”| Method | Description | Defined by |
|---|---|---|
__construct() | Constructor. | yii\ |
__call() | Calls the named method which is not a class method. | yii\ |
__clone() | This method is called after the object is created by cloning an existing one. | yii\ |
__get() | Returns the value of a component property. | yii\ |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\ |
__set() | Sets the value of a component property. | yii\ |
__unset() | Sets a component property to be null. | yii\ |
attachBehavior() | Attaches a behavior to this component. | yii\ |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\ |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\ |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\ |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\ |
checkBasePathPermission() | Check whether the basePath exists and is writeable. | AssetManager |
className() static | Returns the fully qualified name of this class. | yii\ |
detachBehavior() | Detaches a behavior from the component. | yii\ |
detachBehaviors() | Detaches all behaviors from the component. | yii\ |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\ |
getActualAssetUrl() | Returns the actual URL for the specified asset. Without parameters. | AssetManager |
getAssetPath() | Returns the actual file path for the specified asset. | AssetManager |
getAssetUrl() | Returns the actual URL for the specified asset. | AssetManager |
getBehavior() | Returns the named behavior object. | yii\ |
getBehaviors() | Returns all behaviors attached to this component. | yii\ |
getBundle() | Returns the named asset bundle. | AssetManager |
getConverter() | Returns the asset converter. | AssetManager |
getPublishedPath() | Returns the published path of a file path. | AssetManager |
getPublishedUrl() | Returns the URL of a published file path. | AssetManager |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\ |
hasMethod() | Returns a value indicating whether a method is defined. | yii\ |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\ |
init() | Initializes the component. | AssetManager |
off() | Detaches an existing event handler from this component. | yii\ |
on() | Attaches an event handler to an event. | yii\ |
publish() | Publishes a file or a directory. | AssetManager |
setConverter() | Sets the asset converter. | AssetManager |
trigger() | Triggers an event. | yii\ |
hash() protected | Generate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash string. | AssetManager |
loadBundle() protected | Loads asset bundle class by name. | AssetManager |
loadDummyBundle() protected | Loads dummy bundle by name. | AssetManager |
publishDirectory() protected | Publishes a directory. | AssetManager |
publishFile() protected | Publishes a file. | AssetManager |
resolveAsset() protected | AssetManager |
Property details
Section titled “Property details”$afterCopy
Section titled “$afterCopy ”public callable|null $afterCopy = nullA 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 FileHelper::copyDirectory().
$appendTimestamp
Section titled “$appendTimestamp ”public bool $appendTimestamp = falseWhether 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.
Since
2.0.3
$assetMap
Section titled “$assetMap ”public string[] $assetMap = []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 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',]$beforeCopy
Section titled “$beforeCopy ”public callable|null $beforeCopy = nullA 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 FileHelper::copyDirectory().
$bundles
Section titled “$bundles ”public array|false $bundles = []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 override a specific asset bundle (e.g. to drop its CSS files, or to
redirect JS/CSS files to a CDN). Replace app\assets\AppAsset with the FQCN of the bundle you want to
customize:
[ 'app\assets\AppAsset' => [ 'css' => [], ],]To remap individual asset files (for example, to serve jquery.js from a CDN or a local build folder), use
$assetMap instead; it maps a source file name to its replacement URL and is resolved at publish/register time.
A bundle may also set its own AssetBundle::$sourcePath to point the entire bundle at an alternate directory.
$converter
Section titled “$converter ”public array|string|yii\web\AssetConverterInterface $converterThe asset converter.
This can be either an
object implementing the AssetConverterInterface, or a configuration array that can be used to create the
asset converter object, or a class name.
$dirMode
Section titled “$dirMode ”public int $dirMode = 0775The 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.
$fileMode
Section titled “$fileMode ”public int|null $fileMode = nullThe 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.
$forceCopy
Section titled “$forceCopy ”public bool $forceCopy = falseWhether 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.
$hashCallback
Section titled “$hashCallback ”public callable|null $hashCallback = nullA 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);}Since
2.0.6
$linkAssets
Section titled “$linkAssets ”public bool $linkAssets = falseWhether 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 FollowSymLinksMethod details
Section titled “Method details”checkBasePathPermission()
Section titled “checkBasePathPermission() ”public function checkBasePathPermission(): mixedCheck whether the basePath exists and is writeable.
Returns
mixed
Since
2.0.40
getActualAssetUrl()
Section titled “getActualAssetUrl() ”public function getActualAssetUrl(yii\web\AssetBundle $bundle, string $asset): stringReturns the actual URL for the specified asset. Without parameters.
The actual URL is obtained by prepending either AssetBundle::$baseUrl or AssetManager::$baseUrl to the given asset path.
Parameters
| Parameter | Type | Description |
|---|---|---|
$bundle | AssetBundle | The asset bundle which the asset file belongs to |
$asset | string | The asset path. This should be one of the assets listed in AssetBundle::$js or AssetBundle::$css. |
Returns
string: The actual URL for the specified asset.
Since
2.0.39
getAssetPath()
Section titled “getAssetPath() ”public function getAssetPath(yii\web\AssetBundle $bundle, string $asset): string|falseReturns the actual file path for the specified asset.
Parameters
| Parameter | Type | Description |
|---|---|---|
$bundle | AssetBundle | The asset bundle which the asset file belongs to |
$asset | string | The asset path. This should be one of the assets listed in AssetBundle::$js or AssetBundle::$css. |
Returns
string|false: The actual file path, or false if the asset is specified as an absolute URL
getAssetUrl()
Section titled “getAssetUrl() ”public function getAssetUrl(yii\web\AssetBundle $bundle, string $asset, bool|null $appendTimestamp = null): stringReturns the actual URL for the specified asset.
The actual URL is obtained by prepending either AssetBundle::$baseUrl or AssetManager::$baseUrl to the given asset path.
Parameters
| Parameter | Type | Description |
|---|---|---|
$bundle | AssetBundle | The asset bundle which the asset file belongs to |
$asset | string | The asset path. This should be one of the assets listed in AssetBundle::$js or AssetBundle::$css. |
$appendTimestamp | bool| | Whether to append timestamp to the URL. |
Returns
string: The actual URL for the specified asset.
getBundle()
Section titled “getBundle() ”public function getBundle(string $name, bool $publish = true): yii\web\AssetBundleReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | The class name of the asset bundle (without the leading backslash) |
$publish | bool | 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. |
Returns
AssetBundle: The asset bundle instance
Throws
yii\base\InvalidConfigException: if $name does not refer to a valid asset bundle
getConverter()
Section titled “getConverter() ”public function getConverter(): yii\web\AssetConverterInterfaceReturns the asset converter.
Returns
AssetConverterInterface: The asset converter.
getPublishedPath()
Section titled “getPublishedPath() ”public function getPublishedPath(string $path): string|falseReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$path | string | Directory or file path being published |
Returns
string|false: String the published file path. False if the file or directory does not exist
getPublishedUrl()
Section titled “getPublishedUrl() ”public function getPublishedUrl(string $path): string|falseReturns 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.
Parameters
| Parameter | Type | Description |
|---|---|---|
$path | string | Directory or file path being published |
Returns
string|false: String the published URL for the file or directory. False if the file or directory does not exist.
publish()
Section titled “publish() ”public function publish(string $path, yii\web\PublishOptions $options = []): arrayPublishes 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
Parameters
| Parameter | Type | Description |
|---|---|---|
$path | string | The asset (file or directory) to be published |
$options | yii\ | 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. |
Returns
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.yii\base\InvalidConfigException: if the target directory$basePathis not writeable.
setConverter()
Section titled “setConverter() ”public function setConverter(array|string|yii\web\AssetConverterInterface $value): mixedSets the asset converter.
Parameters
| Parameter | Type | Description |
|---|---|---|
$value | array|AssetConverterInterface | The asset converter. This can be either an object implementing the AssetConverterInterface, or a configuration array that can be used to create the asset converter object, or a class name. |
Returns
mixed
hash()
Section titled “hash() ”protected function hash(string $path): stringGenerate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash string.
Parameters
| Parameter | Type | Description |
|---|---|---|
$path | string | String to be hashed. |
Returns
string: Hashed string.
loadBundle()
Section titled “loadBundle() ”protected function loadBundle(string $name, array $config = [], bool $publish = true): yii\web\AssetBundleLoads asset bundle class by name.
Parameters
| Parameter | Type | Description |
|---|---|---|
$name | string | Bundle name |
$config | array | Bundle object configuration |
$publish | bool | If bundle should be published |
Returns
Throws
yii\base\InvalidConfigException: if configuration isn’t valid
loadDummyBundle()
Section titled “loadDummyBundle() ”protected function loadDummyBundle(string $name): yii\web\AssetBundleLoads dummy bundle by name.
publishDirectory()
Section titled “publishDirectory() ”protected function publishDirectory(string $src, array $options): string[]Publishes a directory.
Parameters
| Parameter | Type | Description |
|---|---|---|
$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. |
Returns
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()
Section titled “publishFile() ”protected function publishFile(string $src): string[]Publishes a file.
Parameters
| Parameter | Type | Description |
|---|---|---|
$src | string | The asset file to be published |
Returns
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()
Section titled “resolveAsset() ”protected function resolveAsset(yii\web\AssetBundle $bundle, string $asset): string|false