CCodeModel

CDbHttpSession

Yii Framework v1.1.10 类参考

CCodeModel

system.gii
继承 abstract class CCodeModel » CFormModel » CModel » CComponent
实现 IteratorAggregate, Traversable, ArrayAccess
源自 1.1.2
版本 $Id: CCodeModel.php 3547 2012-01-24 10:07:28Z mdomba $
源码 framework/gii/CCodeModel.php
CCodeModel是代码生成时用到的各种模型类的基类。

每一个代码生成器至少需要有一个从此类扩展而来的代码模型类。 一个代码模型的作用是表示用户提供的参数,并使用它们来生成自 定义的代码。

派生类需要实现prepare方法,此方法的主要任务是 基于用户参数填充files属性。

files属性将被若干CCodeFile实例组成的集合填充, 每个实例表示将生成的一个单一的代码文件。

CCodeModel实现了粘连属性(sticky attributes)的功能。一个粘连 属性可以记忆它的最后的有效值,即使用户已经关闭然后再打开浏览器。 要定义一个属性为粘连属性,只需要简单地将它加入到名为“sticky” 的验证器的验证规则列表中。

公共属性

隐藏继承属性

属性类型描述定义在
answers array 用户对是否以新生成的代码文件覆盖原有的代码文件的确认信息。 此属性的值通过此类和CCodeGenerator内部管理。 CCodeModel
attributes array Returns all attribute values. CModel
errors array Returns the errors for all attribute or a single attribute. CModel
files array CCodeFile对象的列表,表示将被生成的代码文件。 prepare()方法负责填充此属性。 CCodeModel
iterator CMapIterator Returns an iterator for traversing the attributes in the model. CModel
keywords CCodeModel
safeAttributeNames array Returns the attribute names that are safe to be massively assigned. CModel
scenario string Returns the scenario that this model is used in. CModel
status integer 此模型的状态。 此属性值通过CCodeGenerator内部管理。 CCodeModel
stickyFile string 存储粘连属性值的文件路径。 CCodeModel
template string 用户选择的代码模板的名字。 此属性的值通过此类和CCodeGenerator内部管理。 CCodeModel
templatePath string 包含模板文件的目录。 CCodeModel
templates array 返回可用的代码模板的列表(name=>directory)。 CCodeModel
validatorList CList Returns all the validators declared in the model. CModel
validators array Returns the validators applicable to the current scenario. CModel

公共方法

隐藏继承方法

方法描述定义在
__call() 如果类中没有调的方法名,则调用这个方法。 CComponent
__construct() 构造方法。 CFormModel
__get() 返回一个属性值、一个事件处理程序列表或一个行为名称。 CComponent
__isset() 检查一个属性是否为null。 CComponent
__set() 设置一个组件的属性值。 CComponent
__unset() 设置一个组件的属性为null。 CComponent
addError() Adds a new error to the specified attribute. CModel
addErrors() Adds a list of errors. CModel
asa() 返回这个名字的行为对象。 CComponent
attachBehavior() 附加一个行为到组件。 CComponent
attachBehaviors() 附加一个行为列表到组件。 CComponent
attachEventHandler() 为事件附加一个事件处理程序。 CComponent
attributeLabels() 声明此模型属性的标签。 CCodeModel
attributeNames() 返回属性名列表。 CFormModel
behaviors() Returns a list of behaviors that this model should behave as. CModel
canGetProperty() 确定属性是否可读。 CComponent
canSetProperty() 确定属性是否可写。 CComponent
class2id() 将一个类的名字转换为一个 HTML ID。 CCodeModel
class2name() 将一个类的名字转换为以空白分隔的单词。 CCodeModel
class2var() 将一个类的名字转换为一个首字母小写的变量名。 CCodeModel
classExists() 检测给定名字的类是否存在(对大小写敏感)。 CCodeModel
clearErrors() Removes errors for all attributes or a single attribute. CModel
confirmed() CCodeModel
createValidators() Creates validator objects based on the specification in rules. CModel
detachBehavior() 从组件中分离一个行为。 CComponent
detachBehaviors() 从组件中分离所有行为。 CComponent
detachEventHandler() 分离一个存在的事件处理程序。 CComponent
disableBehavior() 禁用一个附加行为。 CComponent
disableBehaviors() 禁用组件附加的所有行为。 CComponent
enableBehavior() 启用一个附加行为。 CComponent
enableBehaviors() 启用组件附加的所有行为。 CComponent
errorMessage() 返回当代码文件保存期间发生错误时需要显示的信息。 CCodeModel
evaluateExpression() 计算一个PHP表达式,或根据组件上下文执行回调。 CComponent
generateAttributeLabel() Generates a user friendly attribute label. CModel
getAttributeLabel() Returns the text label for the specified attribute. CModel
getAttributes() Returns all attribute values. CModel
getError() Returns the first error of the specified attribute. CModel
getErrors() Returns the errors for all attribute or a single attribute. CModel
getEventHandlers() 返回一个事件的附加处理程序列表。 CComponent
getIterator() Returns an iterator for traversing the attributes in the model. CModel
getSafeAttributeNames() Returns the attribute names that are safe to be massively assigned. CModel
getScenario() Returns the scenario that this model is used in. CModel
getStickyFile() 返回存储粘连属性值的文件路径。 CCodeModel
getTemplatePath() 返回包含模板文件的目录。 CCodeModel
getTemplates() 返回可用的代码模板的列表(name=>directory)。 CCodeModel
getValidatorList() Returns all the validators declared in the model. CModel
getValidators() Returns the validators applicable to the current scenario. CModel
hasErrors() Returns a value indicating whether there is any validation error. CModel
hasEvent() 确定一个事件是否定义。 CComponent
hasEventHandler() 检查事件是否有附加的处理程序。 CComponent
hasProperty() 确定属性是否被定义。 CComponent
init() 初始化模型。 CFormModel
isAttributeRequired() Returns a value indicating whether the attribute is required. CModel
isAttributeSafe() Returns a value indicating whether the attribute is safe for massive assignments. CModel
loadStickyAttributes() 从文件中载入粘连属性值然后将它们填充到模型中。 CCodeModel
offsetExists() Returns whether there is an element at the specified offset. CModel
offsetGet() Returns the element at the specified offset. CModel
offsetSet() Sets the element at the specified offset. CModel
offsetUnset() Unsets the element at the specified offset. CModel
onAfterConstruct() This event is raised after the model instance is created by new operator. CModel
onAfterValidate() This event is raised after the validation is performed. CModel
onBeforeValidate() This event is raised before the validation is performed. CModel
onUnsafeAttribute() This method is invoked when an unsafe attribute is being massively assigned. CModel
pluralize() 将一个单词转换为复数形式。 CCodeModel
prepare() 准备将生成的代码文件。 CCodeModel
raiseEvent() 发起一个事件。 CComponent
render() 使用指定的代码模板文件生成代码。 CCodeModel
renderResults() CCodeModel
requiredTemplates() 返回必需的代码模板的列表。 CCodeModel
rules() 声明此模型的验证规则。 CCodeModel
save() 将生成的代码保存到若干文件中。 CCodeModel
saveStickyAttributes() 保存粘连属性值到一个文件中。 CCodeModel
setAttributes() Sets the attribute values in a massive way. CModel
setScenario() Sets the scenario for the model. CModel
sticky() 粘连验证器(The "sticky" validator)。 CCodeModel
successMessage() 返回当新生成的代码成功保存到文件中时需要显示的信息。 CCodeModel
unsetAttributes() Sets the attributes to be null. CModel
validate() Performs the validation. CModel
validateReservedWord() 验证一个属性没有使用PHP的保留关键字。 CCodeModel
validateTemplate() 验证模板的选择。 CCodeModel

受保护方法

隐藏继承方法

方法描述定义在
afterConstruct() This method is invoked after a model instance is created by new operator. CModel
afterValidate() This method is invoked after validation ends. CModel
beforeValidate() This method is invoked before validation starts. CModel

事件

隐藏继承事件

事件描述定义在
onAfterConstruct This event is raised after the model instance is created by new operator. CModel
onBeforeValidate This event is raised before the validation is performed. CModel
onAfterValidate This event is raised after the validation is performed. CModel
onUnsafeAttribute This method is invoked when an unsafe attribute is being massively assigned. CModel

属性详细

answers 属性
public array $answers;

用户对是否以新生成的代码文件覆盖原有的代码文件的确认信息。 此属性的值通过此类和CCodeGenerator内部管理。

files 属性
public array $files;

CCodeFile对象的列表,表示将被生成的代码文件。 prepare()方法负责填充此属性。

keywords 属性
public static $keywords;

status 属性
public integer $status;

此模型的状态。 此属性值通过CCodeGenerator内部管理。

stickyFile 属性 只读
public string getStickyFile()

存储粘连属性值的文件路径。

template 属性
public string $template;

用户选择的代码模板的名字。 此属性的值通过此类和CCodeGenerator内部管理。

templatePath 属性 只读
public string getTemplatePath()

包含模板文件的目录。

templates 属性 只读
public array getTemplates()

返回可用的代码模板的列表(name=>directory)。 此方法简单地返回CCodeGenerator::templates属性值。

方法详细

attributeLabels() 方法
public array attributeLabels()
{return} array 属性的标签
源码: framework/gii/CCodeModel.php#215 (显示)
public function attributeLabels()
{
    return array(
        
'template'=>'Code Template',
    );
}

声明此模型属性的标签。 子类必须按下列格式覆盖此方法:

return array_merge(parent::attributeLabels(), array(
    ...labels for the child class attributes...
));

class2id() 方法
public string class2id(string $name)
$name string 需要转换的字符串
{return} string 转换的结果
源码: framework/gii/CCodeModel.php#440 (显示)
public function class2id($name)
{
    return 
trim(strtolower(str_replace('_','-',preg_replace('/(?<![A-Z])[A-Z]/''-\0'$name))),'-');
}

将一个类的名字转换为一个 HTML ID。 例如,'PostTag'将转换为'post-tag'。

class2name() 方法
public string class2name(string $name, boolean $ucwords=true)
$name string 需要数的的字符串。
$ucwords boolean 是否将每个单词的首字母转为大写
{return} string 转换的结果
源码: framework/gii/CCodeModel.php#452 (显示)
public function class2name($name,$ucwords=true)
{
    
$result=trim(strtolower(str_replace('_',' ',preg_replace('/(?<![A-Z])[A-Z]/'' \0'$name))));
    return 
$ucwords ucwords($result) : $result;
}

将一个类的名字转换为以空白分隔的单词。 例如,'PostTag'将转换为'Post Tag'。

class2var() 方法 (可用自 v1.1.4)
public string class2var(string $name)
$name string 类的名字
{return} string 从类的名字转换而来的变量名字
源码: framework/gii/CCodeModel.php#465 (显示)
public function class2var($name)
{
    
$name[0]=strtolower($name[0]);
    return 
$name;
}

将一个类的名字转换为一个首字母小写的变量名。 之所以提供此方法,是因为PHP函数lcfirst()只在 PHP5.3+ 可用。

classExists() 方法
public boolean classExists(string $name)
$name string 需要检测的类的名字
{return} boolean 此类是否存在
源码: framework/gii/CCodeModel.php#200 (显示)
public function classExists($name)
{
    return 
class_exists($name,false) && in_array($nameget_declared_classes());
}

检测给定名字的类是否存在(对大小写敏感)。

confirmed() 方法
public void confirmed(CCodeFile $file)
$file CCodeFile 将被保存的代码文件
源码: framework/gii/CCodeModel.php#296 (显示)
public function confirmed($file)
{
    return 
$this->answers===null && $file->operation===CCodeFile::OP_NEW
        
|| is_array($this->answers) && isset($this->answers[md5($file->path)]);
}

errorMessage() 方法
public string errorMessage()
{return} string 当代码文件保存期间发生错误时需要显示的信息。
源码: framework/gii/CCodeModel.php#262 (显示)
public function errorMessage()
{
    return 
'There was some error when generating the code. Please check the following messages.';
}

返回当代码文件保存期间发生错误时需要显示的信息。 如果子类需要自定义错误提示信息就覆盖此方法。

getStickyFile() 方法
public string getStickyFile()
{return} string 存储粘连属性值的文件路径。
源码: framework/gii/CCodeModel.php#393 (显示)
public function getStickyFile()
{
    return 
Yii::app()->runtimePath.'/gii-'.Yii::getVersion().'/'.get_class($this).'.php';
}

getTemplatePath() 方法
public string getTemplatePath()
{return} string 包含模板文件的目录。
源码: framework/gii/CCodeModel.php#281 (显示)
public function getTemplatePath()
{
    
$templates=$this->getTemplates();
    if(isset(
$templates[$this->template]))
        return 
$templates[$this->template];
    else if(empty(
$templates))
        throw new 
CHttpException(500,'No templates are available.');
    else
        throw new 
CHttpException(500,'Invalid template selection.');

}

getTemplates() 方法
public array getTemplates()
{return} array 可用的代码模板的列表(name=>directory)。
源码: framework/gii/CCodeModel.php#272 (显示)
public function getTemplates()
{
    return 
Yii::app()->controller->templates;
}

返回可用的代码模板的列表(name=>directory)。 此方法简单地返回CCodeGenerator::templates属性值。

loadStickyAttributes() 方法
public void loadStickyAttributes()
源码: framework/gii/CCodeModel.php#361 (显示)
public function loadStickyAttributes()
{
    
$this->_stickyAttributes=array();
    
$path=$this->getStickyFile();
    if(
is_file($path))
    {
        
$result=@include($path);
        if(
is_array($result))
        {
            
$this->_stickyAttributes=$result;
            foreach(
$this->_stickyAttributes as $name=>$value)
            {
                if(
property_exists($this,$name) || $this->canSetProperty($name))
                    
$this->$name=$value;
            }
        }
    }
}

从文件中载入粘连属性值然后将它们填充到模型中。

pluralize() 方法
public string pluralize(string $name)
$name string 需要转为复数的单词
{return} string 单词的复数
源码: framework/gii/CCodeModel.php#405 (显示)
public function pluralize($name)
{
    
$rules=array(
        
'/move$/i' => 'moves',
        
'/foot$/i' => 'feet',
        
'/child$/i' => 'children',
        
'/human$/i' => 'humans',
        
'/man$/i' => 'men',
        
'/tooth$/i' => 'teeth',
        
'/person$/i' => 'people',
        
'/([m|l])ouse$/i' => '\1ice',
        
'/(x|ch|ss|sh|us|as|is|os)$/i' => '\1es',
        
'/([^aeiouy]|qu)y$/i' => '\1ies',
        
'/(?:([^f])fe|([lr])f)$/i' => '\1\2ves',
        
'/(shea|lea|loa|thie)f$/i' => '\1ves',
        
'/([ti])um$/i' => '\1a',
        
'/(tomat|potat|ech|her|vet)o$/i' => '\1oes',
        
'/(bu)s$/i' => '\1ses',
        
'/(ax|test)is$/i' => '\1es',
        
'/s$/' => 's',
    );
    foreach(
$rules as $rule=>$replacement)
    {
        if(
preg_match($rule,$name))
            return 
preg_replace($rule,$replacement,$name);
    }
    return 
$name.'s';
}

将一个单词转换为复数形式。 注意:此方法仅针对英语! 例如,'apple'将转换为'apples',而'child'将转换为'children'。

prepare() 方法
abstract public void prepare()
源码: framework/gii/CCodeModel.php#151 (显示)
abstract public function prepare();

准备将生成的代码文件。 这是子类需要实现的主要方法,它包含了使用将要生成 的代码文件的列表填充files属性的逻辑。

render() 方法
public string render(string $templateFile, array $_params_=NULL)
$templateFile string 代码模板文件路径
$_params_ array 被提取到代码模板中使用的参数的集合
{return} string 生成的代码
源码: framework/gii/CCodeModel.php#309 (显示)
public function render($templateFile,$_params_=null)
{
    if(!
is_file($templateFile))
        throw new 
CException("The template file '$templateFile' does not exist.");

    if(
is_array($_params_))
        
extract($_params_,EXTR_PREFIX_SAME,'params');
    else
        
$params=$_params_;
    
ob_start();
    
ob_implicit_flush(false);
    require(
$templateFile);
    return 
ob_get_clean();
}

使用指定的代码模板文件生成代码。 此方法主要在generate中被用于生成代码。

renderResults() 方法
public string renderResults()
{return} string 代码生成的结果日志。
源码: framework/gii/CCodeModel.php#327 (显示)
public function renderResults()
{
    
$output='Generating code using template "'.$this->templatePath."\"...\n";
    foreach(
$this->files as $file)
    {
        if(
$file->error!==null)
            
$output.="<span class=\"error\">generating {$file->relativePath}<br/>           {$file->error}</span>\n";
        else if(
$file->operation===CCodeFile::OP_NEW && $this->confirmed($file))
            
$output.=' generated '.$file->relativePath."\n";
        else if(
$file->operation===CCodeFile::OP_OVERWRITE && $this->confirmed($file))
            
$output.=' overwrote '.$file->relativePath."\n";
        else
            
$output.='   skipped '.$file->relativePath."\n";
    }
    
$output.="done!\n";
    return 
$output;
}

requiredTemplates() 方法
public array requiredTemplates()
{return} array 必需的代码模板的列表,它们是与 templatePath相关联的文件路径。
源码: framework/gii/CCodeModel.php#228 (显示)
public function requiredTemplates()
{
    return array();
}

返回必需的代码模板的列表。 派生类通常需要覆盖此方法。

rules() 方法
public array rules()
{return} array 验证规则
源码: framework/gii/CCodeModel.php#163 (显示)
public function rules()
{
    return array(
        array(
'template''required'),
        array(
'template''validateTemplate''skipOnError'=>true),
        array(
'template''sticky'),
    );
}

声明此模型的验证规则。 子类必须按下列格式覆盖此方法:

return array_merge(parent::rules(), array(
    ...rules for the child class...
));

save() 方法
public void save()
源码: framework/gii/CCodeModel.php#236 (显示)
public function save()
{
    
$result=true;
    foreach(
$this->files as $file)
    {
        if(
$this->confirmed($file))
            
$result=$file->save() && $result;
    }
    return 
$result;
}

将生成的代码保存到若干文件中。

saveStickyAttributes() 方法
public void saveStickyAttributes()
源码: framework/gii/CCodeModel.php#383 (显示)
public function saveStickyAttributes()
{
    
$path=$this->getStickyFile();
    @
mkdir(dirname($path),0755,true);
    
file_put_contents($path,"<?php\nreturn ".var_export($this->_stickyAttributes,true).";\n");
}

保存粘连属性值到一个文件中。

sticky() 方法
public void sticky(string $attribute, array $params)
$attribute string 需要验证的属性
$params array 验证参数
源码: framework/gii/CCodeModel.php#352 (显示)
public function sticky($attribute,$params)
{
    if(!
$this->hasErrors())
        
$this->_stickyAttributes[$attribute]=$this->$attribute;
}

粘连验证器(The "sticky" validator)。 此验证器并不真的对属性进行验证, 它实际上是将此属性的值保存在一个文件中以使属性支持粘连功能。

successMessage() 方法
public string successMessage()
{return} string 当新生成的代码成功保存到文件中时需要显示的信息。
源码: framework/gii/CCodeModel.php#252 (显示)
public function successMessage()
{
    return 
'The code has been generated successfully.';
}

返回当新生成的代码成功保存到文件中时需要显示的信息。 如果子类需要自定义提示信息就覆盖此方法。

validateReservedWord() 方法
public void validateReservedWord(string $attribute, array $params)
$attribute string 需要验证的属性
$params array 验证参数
源码: framework/gii/CCodeModel.php#476 (显示)
public function validateReservedWord($attribute,$params)
{
    
$value=$this->$attribute;
    if(
in_array(strtolower($value),self::$keywords))
        
$this->addError($attribute$this->getAttributeLabel($attribute).' cannot take a reserved PHP keyword.');
}

验证一个属性没有使用PHP的保留关键字。

validateTemplate() 方法
public void validateTemplate(string $attribute, array $params)
$attribute string 需要验证的属性
$params array 验证参数
源码: framework/gii/CCodeModel.php#179 (显示)
public function validateTemplate($attribute,$params)
{
    
$templates=$this->templates;
    if(!isset(
$templates[$this->template]))
        
$this->addError('template''Invalid template selection.');
    else
    {
        
$templatePath=$this->templatePath;
        foreach(
$this->requiredTemplates() as $template)
        {
            if(!
is_file($templatePath.'/'.$template))
                
$this->addError('template'"Unable to find the required code template file '$template'.");
        }
    }
}

验证模板的选择。 此方法验证用户是否选择了一个存在的模板,且此模板包含有 所有在requiredTemplates中指定的必需的模板文件。

Copyright © 2008-2011 by Yii Software LLC
All Rights Reserved.