system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CCodeModel

system.gii
继承 abstract class CCodeModel » CFormModel » CModel » CComponent
实现 IteratorAggregate, Traversable, ArrayAccess
可用自 1.1.2
源码 framework/gii/CCodeModel.php
CCodeModel is the base class for model classes that are used to generate code.

Each code generator should have at least one code model class that extends from this class. The purpose of a code model is to represent user-supplied parameters and use them to generate customized code.

Derived classes should implement the prepare method whose main task is to fill up the files property based on the user parameters.

The files property should be filled with a set of CCodeFile instances, each representing a single code file to be generated.

CCodeModel implements the feature of "sticky attributes". A sticky attribute is an attribute that can remember its last valid value, even if the user closes his browser window and reopen it. To declare an attribute is sticky, simply list it in a validation rule with the validator name being "sticky".

公共属性

隐藏继承的属性

属性类型描述被定义在
answers array user confirmations on whether to overwrite existing code files with the newly generated ones. CCodeModel
attributes array Returns all attribute values. CModel
errors array Returns the errors for all attribute or a single attribute. CModel
files array a list of CCodeFile objects that represent the code files to be generated. 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 the status of this model. CCodeModel
stickyFile string the file path that stores the sticky attribute values. CCodeModel
template string the name of the code template that the user has selected. CCodeModel
templatePath string the directory that contains the template files. CCodeModel
templates array Returns a list of available code templates (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() Calls the named method which is not a class method. CComponent
__construct() Constructor. CFormModel
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
addError() Adds a new error to the specified attribute. CModel
addErrors() Adds a list of errors. CModel
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
attributeLabels() Declares the model attribute labels. CCodeModel
attributeNames() Returns the list of attribute names. CFormModel
behaviors() Returns a list of behaviors that this model should behave as. CModel
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
class2id() Converts a class name into a HTML ID. CCodeModel
class2name() Converts a class name into space-separated words. CCodeModel
class2var() Converts a class name into a variable name with the first letter in lower case. CCodeModel
classExists() Checks if the named class exists (in a case sensitive manner). 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() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
errorMessage() Returns the message to be displayed when some error occurred during code file saving. CCodeModel
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. 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() Returns the list of attached event handlers for an event. 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() Returns the file path that stores the sticky attribute values. CCodeModel
getTemplatePath() Returns the directory that contains the template files. CCodeModel
getTemplates() Returns a list of available code templates (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() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Initializes this model. 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() Loads sticky attributes from a file and populates them into the model. 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() Converts a word to its plural form. CCodeModel
prepare() Prepares the code files to be generated. CCodeModel
raiseEvent() Raises an event. CComponent
render() Generates the code using the specified code template file. CCodeModel
renderResults() CCodeModel
requiredTemplates() Returns a list of code templates that are required. CCodeModel
rules() Declares the model validation rules. CCodeModel
save() Saves the generated code into files. CCodeModel
saveStickyAttributes() Saves sticky attributes into a file. 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() Returns the message to be displayed when the newly generated code is saved successfully. CCodeModel
unsetAttributes() Sets the attributes to be null. CModel
validate() Performs the validation. CModel
validateReservedWord() Validates an attribute to make sure it is not taking a PHP reserved keyword. CCodeModel
validateTemplate() Validates the template selection. 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;

user confirmations on whether to overwrite existing code files with the newly generated ones. The value of this property is internally managed by this class and CCodeGenerator.

files 属性
public array $files;

a list of CCodeFile objects that represent the code files to be generated. The prepare() method is responsible to populate this property.

keywords 属性
public static $keywords;

status 属性
public integer $status;

the status of this model. T The value of this property is internally managed by CCodeGenerator.

stickyFile 属性 只读
public string getStickyFile()

the file path that stores the sticky attribute values.

template 属性
public string $template;

the name of the code template that the user has selected. The value of this property is internally managed by this class and CCodeGenerator.

templatePath 属性 只读
public string getTemplatePath()

the directory that contains the template files.

templates 属性 只读
public array getTemplates()

Returns a list of available code templates (name=>directory). This method simply returns the CCodeGenerator::templates property value.

方法详情

attributeLabels() 方法
public array attributeLabels()
{return} array the attribute labels
源码: framework/gii/CCodeModel.php#214 (显示)
public function attributeLabels()
{
    return array(
        
'template'=>'Code Template',
    );
}

Declares the model attribute labels. Child classes must override this method in the following format:

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

class2id() 方法
public string class2id(string $name)
$name string the string to be converted
{return} string the resulting ID
源码: framework/gii/CCodeModel.php#442 (显示)
public function class2id($name)
{
    return 
trim(strtolower(str_replace('_','-',preg_replace('/(?<![A-Z])[A-Z]/''-\0'$name))),'-');
}

Converts a class name into a HTML ID. For example, 'PostTag' will be converted as 'post-tag'.

class2name() 方法
public string class2name(string $name, boolean $ucwords=true)
$name string the string to be converted
$ucwords boolean whether to capitalize the first letter in each word
{return} string the resulting words
源码: framework/gii/CCodeModel.php#454 (显示)
public function class2name($name,$ucwords=true)
{
    
$result=trim(strtolower(str_replace('_',' ',preg_replace('/(?<![A-Z])[A-Z]/'' \0'$name))));
    return 
$ucwords ucwords($result) : $result;
}

Converts a class name into space-separated words. For example, 'PostTag' will be converted as 'Post Tag'.

class2var() 方法 (自版本 v1.1.4 可用)
public string class2var(string $name)
$name string the class name
{return} string the variable name converted from the class name
源码: framework/gii/CCodeModel.php#467 (显示)
public function class2var($name)
{
    
$name[0]=strtolower($name[0]);
    return 
$name;
}

Converts a class name into a variable name with the first letter in lower case. This method is provided because lcfirst() PHP function is only available for PHP 5.3+.

classExists() 方法
public boolean classExists(string $name)
$name string class name to be checked
{return} boolean whether the class exists
源码: framework/gii/CCodeModel.php#199 (显示)
public function classExists($name)
{
    return 
class_exists($name,false) && in_array($nameget_declared_classes());
}

Checks if the named class exists (in a case sensitive manner).

confirmed() 方法
public bool confirmed(CCodeFile $file)
$file CCodeFile whether the code file should be saved
{return} bool whether the confirmation is found in answers with appropriate operation
源码: 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 the message to be displayed when some error occurred during code file saving.
源码: framework/gii/CCodeModel.php#261 (显示)
public function errorMessage()
{
    return 
'There was some error when generating the code. Please check the following messages.';
}

Returns the message to be displayed when some error occurred during code file saving. Child classes should override this method if the message needs to be customized.

getStickyFile() 方法
public string getStickyFile()
{return} string the file path that stores the sticky attribute values.
源码: framework/gii/CCodeModel.php#394 (显示)
public function getStickyFile()
{
    return 
Yii::app()->runtimePath.'/gii-'.Yii::getVersion().'/'.get_class($this).'.php';
}

getTemplatePath() 方法
public string getTemplatePath()
{return} string the directory that contains the template files.
源码: framework/gii/CCodeModel.php#280 (显示)
public function getTemplatePath()
{
    
$templates=$this->getTemplates();
    if(isset(
$templates[$this->template]))
        return 
$templates[$this->template];
    elseif(empty(
$templates))
        throw new 
CHttpException(500,'No templates are available.');
    else
        throw new 
CHttpException(500,'Invalid template selection.');

}

getTemplates() 方法
public array getTemplates()
{return} array a list of available code templates (name=>directory).
源码: framework/gii/CCodeModel.php#271 (显示)
public function getTemplates()
{
    return 
Yii::app()->controller->templates;
}

Returns a list of available code templates (name=>directory). This method simply returns the CCodeGenerator::templates property value.

loadStickyAttributes() 方法
public void loadStickyAttributes()
源码: framework/gii/CCodeModel.php#362 (显示)
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;
            }
        }
    }
}

Loads sticky attributes from a file and populates them into the model.

pluralize() 方法
public string pluralize(string $name)
$name string the word to be pluralized
{return} string the pluralized word
源码: framework/gii/CCodeModel.php#406 (显示)
public function pluralize($name)
{
    
$rules=array(
        
'/(m)ove$/i' => '\1oves',
        
'/(f)oot$/i' => '\1eet',
        
'/(c)hild$/i' => '\1hildren',
        
'/(h)uman$/i' => '\1umans',
        
'/(m)an$/i' => '\1en',
        
'/(s)taff$/i' => '\1taff',
        
'/(t)ooth$/i' => '\1eeth',
        
'/(p)erson$/i' => '\1eople',
        
'/([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';
}

Converts a word to its plural form. Note that this is for English only! For example, 'apple' will become 'apples', and 'child' will become 'children'.

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

Prepares the code files to be generated. This is the main method that child classes should implement. It should contain the logic that populates the files property with a list of code files to be generated.

render() 方法
public string render(string $templateFile, array $_params_=NULL)
$templateFile string the code template file path
$_params_ array a set of parameters to be extracted and made available in the code template
{return} string the generated code
源码: framework/gii/CCodeModel.php#310 (显示)
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();
}

Generates the code using the specified code template file. This method is manly used in generate to generate code.

renderResults() 方法
public string renderResults()
{return} string the code generation result log.
源码: framework/gii/CCodeModel.php#328 (显示)
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";
        elseif(
$file->operation===CCodeFile::OP_NEW && $this->confirmed($file))
            
$output.=' generated '.$file->relativePath."\n";
        elseif(
$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 list of code templates that are required. They should be file paths relative to templatePath.
源码: framework/gii/CCodeModel.php#227 (显示)
public function requiredTemplates()
{
    return array();
}

Returns a list of code templates that are required. Derived classes usually should override this method.

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

Declares the model validation rules. Child classes must override this method in the following format:

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

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

Saves the generated code into files.

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

Saves sticky attributes into a file.

sticky() 方法
public void sticky(string $attribute, array $params)
$attribute string the attribute to be validated
$params array the validation parameters
源码: framework/gii/CCodeModel.php#353 (显示)
public function sticky($attribute,$params)
{
    if(!
$this->hasErrors())
        
$this->_stickyAttributes[$attribute]=$this->$attribute;
}

The "sticky" validator. This validator does not really validate the attributes. It actually saves the attribute value in a file to make it sticky.

successMessage() 方法
public string successMessage()
{return} string the message to be displayed when the newly generated code is saved successfully.
源码: framework/gii/CCodeModel.php#251 (显示)
public function successMessage()
{
    return 
'The code has been generated successfully.';
}

Returns the message to be displayed when the newly generated code is saved successfully. Child classes should override this method if the message needs to be customized.

validateReservedWord() 方法
public void validateReservedWord(string $attribute, array $params)
$attribute string the attribute to be validated
$params array validation parameters
源码: framework/gii/CCodeModel.php#478 (显示)
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.');
}

Validates an attribute to make sure it is not taking a PHP reserved keyword.

validateTemplate() 方法
public void validateTemplate(string $attribute, array $params)
$attribute string the attribute to be validated
$params array validation parameters
源码: framework/gii/CCodeModel.php#178 (显示)
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'.");
        }
    }
}

Validates the template selection. This method validates whether the user selects an existing template and the template contains all required template files as specified in requiredTemplates.