> YII 类库手册 > CAssetManager
system.web
继承 class CAssetManager » CApplicationComponent » CComponent
实现 IApplicationComponent
源自 1.0
版本 $Id: CAssetManager.php 3449 2011-11-20 20:42:45Z alexander.makarow $
源码
CAssetManager 是一个应用组件,它可以管理私有文件(称之为 assets)并且让用户可以访问到。

实现这个功能的方式就是复制这些文件到一个Web可访问目录下, 并且返回这个目录所对应的可访问URL。

如果要发布一个asset,只需要调用 publish().

Web可访问目录由 basePath 指定。 默认是assets目录。 在这个目录下,储存着整个应用的这类文件。 属性 baseUrl 指向 basePath 的可访问URL。

公共属性

属性 类型 描述 定义在
basePath string the root directory storing the published asset files. CAssetManager
baseUrl string the base url that the published asset files can be Accessed. CAssetManager
behaviors array 这个应用组件附加的行为。 这此行为将在应用组件调用init时附加在应用组件上。 请参照CModel::behaviors如何指定此属性值。 CApplicationComponent
excludeFiles array list of directories and files which should be excluded from the publishing process. CAssetManager
isInitialized boolean 检查应用组件是否已经初始化。 CApplicationComponent
linkAssets boolean whether to use symbolic link to publish asset files. CAssetManager
newDirMode integer the permission to be set for newly generated asset directories. CAssetManager
newFileMode integer the permission to be set for newly generated asset files. CAssetManager

公共方法

方法 描述 定义在
__call() 如果类中没有调的方法名,则调用这个方法。 CComponent
__get() 返回一个属性值、一个事件处理程序列表或一个行为名称。 CComponent
__isset() 检查一个属性是否为null。 CComponent
__set() 设置一个组件的属性值。 CComponent
__unset() 设置一个组件的属性为null。 CComponent
asa() 返回这个名字的行为对象。 CComponent
attachBehavior() 附加一个行为到组件。 CComponent
attachBehaviors() 附加一个行为列表到组件。 CComponent
attachEventHandler() 为事件附加一个事件处理程序。 CComponent
canGetProperty() 确定属性是否可读。 CComponent
canSetProperty() 确定属性是否可写。 CComponent
detachBehavior() 从组件中分离一个行为。 CComponent
detachBehaviors() 从组件中分离所有行为。 CComponent
detachEventHandler() 分离一个存在的事件处理程序。 CComponent
disableBehavior() 禁用一个附加行为。 CComponent
disableBehaviors() 禁用组件附加的所有行为。 CComponent
enableBehavior() 启用一个附加行为。 CComponent
enableBehaviors() 启用组件附加的所有行为。 CComponent
evaLuateExpression() 计算一个PHP表达式,或根据组件上下文执行回调。 CComponent
getBasePath() 返回the root directory storing the published asset files. Defaults to 'WebRoot/assets'. CAssetManager
getBaseUrl() 返回the base url that the published asset files can be accessed. Note, the ending slashes are stripped off. Defaults to '/AppBaseUrl/assets'. CAssetManager
getEventHandlers() 返回一个事件的附加处理程序列表。 CComponent
getIsInitialized() 检查应用组件是否已经初始化。 CApplicationComponent
getPublishedPath() Returns the published path of a file path. CAssetManager
getPublishedUrl() Returns the URL of a published file path. CAssetManager
hasEvent() 确定一个事件是否定义。 CComponent
hasEventHandler() 检查事件是否有附加的处理程序。 CComponent
hasProperty() 确定属性是否被定义。 CComponent
init() 初始化应用组件。 CApplicationComponent
publish() Publishes a file or a directory. CAssetManager
raiseEvent() 发起一个事件。 CComponent
setBasePath() Sets the root directory storing published asset files. CAssetManager
setBaseUrl() 设置the base url that the published asset files can be accessed CAssetManager

受保护方法

方法 描述 定义在
hash() Generate a CRC32 hash for the directory path. Collisions are higher CAssetManager

属性详细

basePath 属性
public string getBasePath()
public void setBasePath(string $value)

the root directory storing the published asset files. Defaults to 'WebRoot/assets'.

baseUrl 属性
public string getBaseUrl()
public void setBaseUrl(string $value)

the base url that the published asset files can be accessed. Note, the ending slashes are stripped off. Defaults to '/AppBaseUrl/assets'.

excludeFiles 属性 (可用自 v1.1.6)
public array $excludeFiles;

list of directories and files which should be excluded from the publishing process. Defaults to exclude '.svn' files only. This option has no effect if linkAssets is enabled.

linkAssets 属性 (可用自 v1.1.5)
public boolean $linkAssets;

whether to use symbolic link to publish asset files. Defaults to false, meaning asset files are copied to public folders. Using symbolic links has the benefit that the published assets will always be consistent with the source assets. 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. The latter requires PHP 5.3 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
newDirMode 属性 (可用自 v1.1.8)
public integer $newDirMode;

the permission to be set for newly generated asset directories. This value will be used by PHP chmod function. Defaults to 0777, meaning the directory can be read, written and executed by all users.

newFileMode 属性 (可用自 v1.1.8)
public integer $newFileMode;

the permission to be set for newly generated asset files. This value will be used by PHP chmod function. Defaults to 0666, meaning the file is read-writable by all users.

方法详细

getBasePath() 方法
public string getBasePath()
{return} string the root directory storing the published asset files. Defaults to 'WebRoot/assets'.
public function getBasePath()
{
    if(
$this->_basePath===null)
    {
        
$request=Yii::app()->getRequest();
        
$this->setBasePath(dirname($request->getScriptFile()).DIRECTORY_SEPARATOR.self::DEFAULT_BASEPATH);
    }
    return 
$this->_basePath;
}

getBaseUrl() 方法
public string getBaseUrl()
{return} string the base url that the published asset files can be accessed. Note, the ending slashes are stripped off. Defaults to '/AppBaseUrl/assets'.
public function getBaseUrl()
{
    if(
$this->_baseUrl===null)
    {
        
$request=Yii::app()->getRequest();
        
$this->setBaseUrl($request->getBaseUrl().'/'.self::DEFAULT_BASEPATH);
    }
    return 
$this->_baseUrl;
}

getPublishedPath() 方法
public string getPublishedPath(string $path, boolean $hashByName=false)
$path string directory or file path being published
$hashByName boolean whether the published directory should be named as the hashed basename. If false, the name will be the hash taken from dirname of the path being published and path mtime. Defaults to false. Set true if the path being published is shared among different extensions.
{return} string the published file path. False if the file or directory does not exist
public function getPublishedPath($path,$hashByName=false)
{
    if((
$path=realpath($path))!==false)
    {
        
$base=$this->getBasePath().DIRECTORY_SEPARATOR;
        if(
is_file($path))
            return 
$base $this->hash($hashByName basename($path) : dirname($path).filemtime($path)) . DIRECTORY_SEPARATOR basename($path);
        else
            return 
$base $this->hash($hashByName basename($path) : $path.filemtime($path));
    }
    else
        return 
false;
}

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.

getPublishedUrl() 方法
public string getPublishedUrl(string $path, boolean $hashByName=false)
$path string directory or file path being published
$hashByName boolean whether the published directory should be named as the hashed basename. If false, the name will be the hash taken from dirname of the path being published and path mtime. Defaults to false. Set true if the path being published is shared among different extensions.
{return} string the published URL for the file or directory. False if the file or directory does not exist.
public function getPublishedUrl($path,$hashByName=false)
{
    if(isset(
$this->_published[$path]))
        return 
$this->_published[$path];
    if((
$path=realpath($path))!==false)
    {
        if(
is_file($path))
            return 
$this->getBaseUrl().'/'.$this->hash($hashByName basename($path) : dirname($path).filemtime($path)).'/'.basename($path);
        else
            return 
$this->getBaseUrl().'/'.$this->hash($hashByName basename($path) : $path.filemtime($path));
    }
    else
        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.

hash() 方法
protected string hash(string $path)
$path string string to be hashed.
{return} string hashed string.
protected function hash($path)
{
    return 
sprintf('%x',crc32($path.Yii::getVersion()));
}

Generate a CRC32 hash for the directory path. Collisions are higher than MD5 but generates a much smaller hash string.

publish() 方法
public string publish(string $path, boolean $hashByName=false, integer $level=-1, boolean $forceCopy=false)
$path string the asset (file or directory) to be published
$hashByName boolean whether the published directory should be named as the hashed basename. If false, the name will be the hash taken from dirname of the path being published and path mtime. Defaults to false. Set true if the path being published is shared among different extensions.
$level integer level of recursive copying when the asset is a directory. Level -1 means publishing all subdirectories and files; Level 0 means publishing only the files DIRECTLY under the directory; level N means copying those directories that are within N levels.
$forceCopy boolean whether we should copy the asset file or directory even if it is already published before. This parameter is set true mainly during development stage when the original assets are being constantly changed. The consequence is that the performance is degraded, which is not a concern during development, however. This parameter has been available since version 1.1.2.
{return} string an absolute URL to the published asset
public function publish($path,$hashByName=false,$level=-1,$forceCopy=false)
{
    if(isset(
$this->_published[$path]))
        return 
$this->_published[$path];
    else if((
$src=realpath($path))!==false)
    {
        if(
is_file($src))
        {
            
$dir=$this->hash($hashByName basename($src) : dirname($src).filemtime($src));
            
$fileName=basename($src);
            
$dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir;
            
$dstFile=$dstDir.DIRECTORY_SEPARATOR.$fileName;

            if(
$this->linkAssets)
            {
                if(!
is_file($dstFile))
                {
                    if(!
is_dir($dstDir))
                    {
                        
mkdir($dstDir);
                        @
chmod($dstDir$this->newDirMode);
                    }
                    
symlink($src,$dstFile);
                }
            }
            else if(@
filemtime($dstFile)<@filemtime($src))
            {
                if(!
is_dir($dstDir))
                {
                    
mkdir($dstDir);
                    @
chmod($dstDir$this->newDirMode);
                }
                
copy($src,$dstFile);
                @
chmod($dstFile$this->newFileMode);
            }

            return 
$this->_published[$path]=$this->getBaseUrl()."/$dir/$fileName";
        }
        else if(
is_dir($src))
        {
            
$dir=$this->hash($hashByName basename($src) : $src.filemtime($src));
            
$dstDir=$this->getBasePath().DIRECTORY_SEPARATOR.$dir;

            if(
$this->linkAssets)
            {
                if(!
is_dir($dstDir))
                    
symlink($src,$dstDir);
            }
            else if(!
is_dir($dstDir) || $forceCopy)
            {
                
CFileHelper::copyDirectory($src,$dstDir,array(
                    
'exclude'=>$this->excludeFiles,
                    
'level'=>$level,
                    
'newDirMode'=>$this->newDirMode,
                    
'newFileMode'=>$this->newFileMode,
                ));
            }

            return 
$this->_published[$path]=$this->getBaseUrl().'/'.$dir;
        }
    }
    throw new 
CException(Yii::t('yii','The asset "{asset}" to be published does not exist.',
        array(
'{asset}'=>$path)));
}

Publishes a file or a directory. This method will copy the specified asset to a web accessible directory and return the URL for accessing the published asset.

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


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
setBasePath() 方法
public void setBasePath(string $value)
$value string the root directory storing published asset files
public function setBasePath($value)
{
    if((
$basePath=realpath($value))!==false && is_dir($basePath) && is_writable($basePath))
        
$this->_basePath=$basePath;
    else
        throw new 
CException(Yii::t('yii','CAssetManager.basePath "{path}" is invalid. Please make sure the directory exists and is writable by the Web server process.',
            array(
'{path}'=>$value)));
}

Sets the root directory storing published asset files.

setBaseUrl() 方法
public void setBaseUrl(string $value)
$value string the base url that the published asset files can be accessed
public function setBaseUrl($value)
{
    
$this->_baseUrl=rtrim($value,'/');
}

上一篇:
下一篇: