Class yii\gii\generators\controller\Generator

Inheritanceyii\gii\generators\controller\Generator » yii\gii\Generator » yii\base\Model
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-gii/blob/master/src/generators/controller/Generator.php

This generator will generate a controller and one or a few action view files.

Public Properties

Hide inherited properties

Property Type Description Defined By
$actionIDs array An array of action IDs entered by the user. yii\gii\generators\controller\Generator
$actions string List of action IDs separated by commas or spaces yii\gii\generators\controller\Generator
$baseClass string The base class of the controller yii\gii\generators\controller\Generator
$controllerClass string The controller class name yii\gii\generators\controller\Generator
$controllerFile string The controller class file path. yii\gii\generators\controller\Generator
$controllerID string The controller ID. yii\gii\generators\controller\Generator
$controllerNamespace string The namespace of the controller class. yii\gii\generators\controller\Generator
$controllerSubPath string The controller sub path. yii\gii\generators\controller\Generator
$description string The detailed description of the generator. yii\gii\Generator
$enableI18N boolean Whether the strings will be generated using Yii::t() or normal strings. yii\gii\Generator
$messageCategory string The message category used by Yii::t() when $enableI18N is true. yii\gii\Generator
$stickyDataFile string The file path that stores the sticky attribute values. yii\gii\Generator
$template string The name of the code template that the user has selected. yii\gii\Generator
$templatePath string The root path of the template files that are currently being used. yii\gii\Generator
$templates array A list of available code templates. yii\gii\Generator
$viewPath string The controller's view path yii\gii\generators\controller\Generator

Public Methods

Hide inherited methods

Method Description Defined By
attributeLabels() yii\gii\generators\controller\Generator
autoCompleteData() Returns the list of auto complete values. yii\gii\Generator
defaultTemplate() Returns the root path to the default code template files. yii\gii\Generator
formView() Returns the view file for the input form of the generator. yii\gii\Generator
generate() Generates the code based on the current user input and the specified code template files. yii\gii\generators\controller\Generator
generateString() Generates a string depending on enableI18N property yii\gii\Generator
getActionIDs() Normalizes $actions into an array of action IDs. yii\gii\generators\controller\Generator
getControllerFile() yii\gii\generators\controller\Generator
getControllerID() yii\gii\generators\controller\Generator
getControllerNamespace() yii\gii\generators\controller\Generator
getControllerSubPath() This method will return sub path for controller if it is located in subdirectory of application controllers dir yii\gii\generators\controller\Generator
getDescription() yii\gii\generators\controller\Generator
getName() yii\gii\generators\controller\Generator
getTemplatePath() yii\gii\Generator
getViewFile() yii\gii\generators\controller\Generator
hints() Returns the list of hint messages. yii\gii\generators\controller\Generator
init() yii\gii\Generator
isReservedKeyword() yii\gii\Generator
render() Generates code using the specified code template and parameters. yii\gii\Generator
requiredTemplates() Returns a list of code template files that are required. yii\gii\generators\controller\Generator
rules() yii\gii\generators\controller\Generator
save() Saves the generated code into files. yii\gii\Generator
stickyAttributes() Returns the list of sticky attributes. yii\gii\generators\controller\Generator
successMessage() Returns the message to be displayed when the newly generated code is saved successfully. yii\gii\generators\controller\Generator
validateClass() An inline validator that checks if the attribute value refers to an existing class name. yii\gii\Generator
validateMessageCategory() Checks if message category is not empty when I18N is enabled. yii\gii\Generator
validateNewClass() An inline validator that checks if the attribute value refers to a valid namespaced class name. yii\gii\Generator
validateTemplate() Validates the template selection. yii\gii\Generator

Property Details

Hide inherited properties

$actionIDs public property

An array of action IDs entered by the user. This property is read-only.

public array $actionIDs null
$actions public property

List of action IDs separated by commas or spaces

public string $actions 'index'
$baseClass public property

The base class of the controller

public string $baseClass 'yii\web\Controller'
$controllerClass public property

The controller class name

public string $controllerClass null
$controllerFile public property

The controller class file path. This property is read-only.

public string $controllerFile null
$controllerID public property

The controller ID. This property is read-only.

public string $controllerID null
$controllerNamespace public property

The namespace of the controller class. This property is read-only.

$controllerSubPath public property

The controller sub path. This property is read-only.

public string $controllerSubPath null
$viewPath public property

The controller's view path

public string $viewPath null

Method Details

Hide inherited methods

attributeLabels() public method

public void attributeLabels ( )

                public function attributeLabels()
{
    return [
        'baseClass' => 'Base Class',
        'controllerClass' => 'Controller Class',
        'viewPath' => 'View Path',
        'actions' => 'Action IDs',
    ];
}

            
autoCompleteData() public method

Defined in: yii\gii\Generator::autoCompleteData()

Returns the list of auto complete values.

The array keys are the attribute names, and the array values are the corresponding auto complete values. Auto complete values can also be callable typed in order one want to make postponed data generation.

public array autoCompleteData ( )
return array

The list of auto complete values

                public function autoCompleteData()
{
    return [];
}

            
defaultTemplate() public method

Defined in: yii\gii\Generator::defaultTemplate()

Returns the root path to the default code template files.

The default implementation will return the "templates" subdirectory of the directory containing the generator class file.

public string defaultTemplate ( )
return string

The root path to the default code template files.

                public function defaultTemplate()
{
    $class = new ReflectionClass($this);
    return dirname($class->getFileName()) . '/default';
}

            
formView() public method

Defined in: yii\gii\Generator::formView()

Returns the view file for the input form of the generator.

The default implementation will return the "form.php" file under the directory that contains the generator class file.

public string formView ( )
return string

The view file for the input form of the generator.

                public function formView()
{
    $class = new ReflectionClass($this);
    return dirname($class->getFileName()) . '/form.php';
}

            
generate() public method

Generates the code based on the current user input and the specified code template files.

This is the main method that child classes should implement. Please refer to yii\gii\generators\controller\Generator::generate() as an example on how to implement this method.

public yii\gii\CodeFile[] generate ( )
return yii\gii\CodeFile[]

A list of code files to be created.

                public function generate()
{
    $files = [];
    $files[] = new CodeFile(
        $this->getControllerFile(),
        $this->render('controller.php')
    );
    foreach ($this->getActionIDs() as $action) {
        $files[] = new CodeFile(
            $this->getViewFile($action),
            $this->render('view.php', ['action' => $action])
        );
    }
    return $files;
}

            
generateString() public method

Defined in: yii\gii\Generator::generateString()

Generates a string depending on enableI18N property

public string generateString ( $string '', $placeholders = [] )
$string string

The text be generated

$placeholders array

The placeholders to use by Yii::t()

                public function generateString($string = '', $placeholders = [])
{
    $string = addslashes($string);
    if ($this->enableI18N) {
        // If there are placeholders, use them
        if (!empty($placeholders)) {
            $ph = ', ' . VarDumper::export($placeholders);
        } else {
            $ph = '';
        }
        $str = "Yii::t('" . $this->messageCategory . "', '" . $string . "'" . $ph . ")";
    } else {
        // No I18N, replace placeholders by real words, if any
        if (!empty($placeholders)) {
            $phKeys = array_map(function($word) {
                return '{' . $word . '}';
            }, array_keys($placeholders));
            $phValues = array_values($placeholders);
            $str = "'" . str_replace($phKeys, $phValues, $string) . "'";
        } else {
            // No placeholders, just the given string
            $str = "'" . $string . "'";
        }
    }
    return $str;
}

            
getActionIDs() public method

Normalizes $actions into an array of action IDs.

public array getActionIDs ( )
return array

An array of action IDs entered by the user

                public function getActionIDs()
{
    $actions = array_unique(preg_split('/[\s,]+/', $this->actions, -1, PREG_SPLIT_NO_EMPTY));
    sort($actions);
    return $actions;
}

            
getControllerFile() public method

public string getControllerFile ( )
return string

The controller class file path

                public function getControllerFile()
{
    return Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\'))) . '.php';
}

            
getControllerID() public method

public string getControllerID ( )
return string

The controller ID

                public function getControllerID()
{
    $name = StringHelper::basename($this->controllerClass);
    return Inflector::camel2id(substr($name, 0, strlen($name) - 10));
}

            
getControllerNamespace() public method

public string getControllerNamespace ( )
return string

The namespace of the controller class

                public function getControllerNamespace()
{
    $name = StringHelper::basename($this->controllerClass);
    return ltrim(substr($this->controllerClass, 0, - (strlen($name) + 1)), '\\');
}

            
getControllerSubPath() public method (available since version 2.0.6)

This method will return sub path for controller if it is located in subdirectory of application controllers dir

See also https://github.com/yiisoft/yii2-gii/issues/182.

public string getControllerSubPath ( )
return string

The controller sub path

                public function getControllerSubPath()
{
    $subPath = '';
    $controllerNamespace = $this->getControllerNamespace();
    if (strpos($controllerNamespace, Yii::$app->controllerNamespace) === 0) {
        $subPath = substr($controllerNamespace, strlen(Yii::$app->controllerNamespace));
        $subPath = ($subPath !== '') ? str_replace('\\', '/', substr($subPath, 1)) . '/' : '';
    }
    return $subPath;
}

            
getDescription() public method

public string getDescription ( )
return string

The detailed description of the generator.

                public function getDescription()
{
    return 'This generator helps you to quickly generate a new controller class with
        one or several controller actions and their corresponding views.';
}

            
getName() public method

public string getName ( )
return string

Name of the code generator

                public function getName()
{
    return 'Controller Generator';
}

            
getTemplatePath() public method
public string getTemplatePath ( )
return string

The root path of the template files that are currently being used.

throws \yii\base\InvalidConfigException

if $template is invalid

                public function getTemplatePath()
{
    if (isset($this->templates[$this->template])) {
        return $this->templates[$this->template];
    }
    throw new InvalidConfigException("Unknown template: {$this->template}");
}

            
getViewFile() public method

public string getViewFile ( $action )
$action string

The action ID

return string

The action view file path

                public function getViewFile($action)
{
    if (empty($this->viewPath)) {
        return Yii::getAlias('@app/views/' . $this->getControllerSubPath() . $this->getControllerID() . "/$action.php");
    }
    return Yii::getAlias(str_replace('\\', '/', $this->viewPath) . "/$action.php");
}

            
hints() public method

Returns the list of hint messages.

The array keys are the attribute names, and the array values are the corresponding hint messages. Hint messages will be displayed to end users when they are filling the form for the generator.

public array hints ( )
return array

The list of hint messages

                public function hints()
{
    return [
        'controllerClass' => 'This is the name of the controller class to be generated. You should
            provide a fully qualified namespaced class (e.g. <code>app\controllers\PostController</code>),
            and class name should be in CamelCase ending with the word <code>Controller</code>. Make sure the class
            is using the same namespace as specified by your application\'s controllerNamespace property.',
        'actions' => 'Provide one or multiple action IDs to generate empty action method(s) in the controller. Separate multiple action IDs with commas or spaces.
            Action IDs should be in lower case. For example:
            <ul>
                <li><code>index</code> generates <code>actionIndex()</code></li>
                <li><code>create-order</code> generates <code>actionCreateOrder()</code></li>
            </ul>',
        'viewPath' => 'Specify the directory for storing the view scripts for the controller. You may use path alias here, e.g.,
            <code>/var/www/basic/controllers/views/order</code>, <code>@app/views/order</code>. If not set, it will default
            to <code>@app/views/ControllerID</code>',
        'baseClass' => 'This is the class that the new controller class will extend from. Please make sure the class exists and can be autoloaded.',
    ];
}

            
init() public method
public void init ( )

                public function init()
{
    parent::init();
    if (!isset($this->templates['default'])) {
        $this->templates['default'] = $this->defaultTemplate();
    }
    foreach ($this->templates as $i => $template) {
        $this->templates[$i] = Yii::getAlias($template);
    }
}

            
isReservedKeyword() public method
public boolean isReservedKeyword ( $value )
$value string

The attribute to be validated

return boolean

Whether the value is a reserved PHP keyword.

                public function isReservedKeyword($value)
{
    static $keywords = [
        '__class__',
        '__dir__',
        '__file__',
        '__function__',
        '__line__',
        '__method__',
        '__namespace__',
        '__trait__',
        'abstract',
        'and',
        'array',
        'as',
        'break',
        'case',
        'catch',
        'callable',
        'cfunction',
        'class',
        'clone',
        'const',
        'continue',
        'declare',
        'default',
        'die',
        'do',
        'echo',
        'else',
        'elseif',
        'empty',
        'enddeclare',
        'endfor',
        'endforeach',
        'endif',
        'endswitch',
        'endwhile',
        'eval',
        'exception',
        'exit',
        'extends',
        'final',
        'finally',
        'for',
        'foreach',
        'function',
        'global',
        'goto',
        'if',
        'implements',
        'include',
        'include_once',
        'instanceof',
        'insteadof',
        'interface',
        'isset',
        'list',
        'namespace',
        'new',
        'old_function',
        'or',
        'parent',
        'php_user_filter',
        'print',
        'private',
        'protected',
        'public',
        'require',
        'require_once',
        'return',
        'static',
        'switch',
        'this',
        'throw',
        'trait',
        'try',
        'unset',
        'use',
        'var',
        'while',
        'xor',
    ];
    return in_array(strtolower($value), $keywords, true);
}

            
render() public method

Defined in: yii\gii\Generator::render()

Generates code using the specified code template and parameters.

Note that the code template will be used as a PHP file.

public string render ( $template, $params = [] )
$template string

The code template file. This must be specified as a file path relative to $templatePath.

$params array

List of parameters to be passed to the template file.

return string

The generated code

                public function render($template, $params = [])
{
    $view = new View();
    $params['generator'] = $this;
    return $view->renderFile($this->getTemplatePath() . '/' . $template, $params, $this);
}

            
requiredTemplates() public method

Returns a list of code template files that are required.

Derived classes usually should override this method if they require the existence of certain template files.

public array requiredTemplates ( )
return array

List of code template files that are required. They should be file paths relative to $templatePath.

                public function requiredTemplates()
{
    return [
        'controller.php',
        'view.php',
    ];
}

            
rules() public method

Child classes should override this method like the following so that the parent rules are included:

return array_merge(parent::rules(), [
    ...rules for the child class...
]);
public void rules ( )

                public function rules()
{
    return array_merge(parent::rules(), [
        [['controllerClass', 'actions', 'baseClass'], 'filter', 'filter' => 'trim'],
        [['controllerClass', 'baseClass'], 'required'],
        ['controllerClass', 'match', 'pattern' => '/^[\w\\\\]*Controller$/', 'message' => 'Only word characters and backslashes are allowed, and the class name must end with "Controller".'],
        ['controllerClass', 'validateNewClass'],
        ['baseClass', 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'],
        ['actions', 'match', 'pattern' => '/^[a-z][a-z0-9\\-,\\s]*$/', 'message' => 'Only a-z, 0-9, dashes (-), spaces and commas are allowed.'],
        ['viewPath', 'safe'],
    ]);
}

            
save() public method

Defined in: yii\gii\Generator::save()

Saves the generated code into files.

public boolean save ( $files, $answers, &$results )
$files yii\gii\CodeFile[]

The code files to be saved

$answers array
$results string

This parameter receives a value from this method indicating the log messages generated while saving the code files.

return boolean

Whether files are successfully saved without any error.

                public function save($files, $answers, &$results)
{
    $lines = ['Generating code using template "' . $this->getTemplatePath() . '"...'];
    $hasError = false;
    foreach ($files as $file) {
        $relativePath = $file->getRelativePath();
        if (isset($answers[$file->id]) && !empty($answers[$file->id]) && $file->operation !== CodeFile::OP_SKIP) {
            $error = $file->save();
            if (is_string($error)) {
                $hasError = true;
                $lines[] = "generating $relativePath\n<span class=\"error\">$error</span>";
            } else {
                $lines[] = $file->operation === CodeFile::OP_CREATE ? " generated $relativePath" : " overwrote $relativePath";
            }
        } else {
            $lines[] = "   skipped $relativePath";
        }
    }
    $lines[] = "done!\n";
    $results = implode("\n", $lines);
    return !$hasError;
}

            
stickyAttributes() public method

Returns the list of sticky attributes.

A sticky attribute will remember its value and will initialize the attribute with this value when the generator is restarted.

public array stickyAttributes ( )
return array

List of sticky attributes

                public function stickyAttributes()
{
    return ['baseClass'];
}

            
successMessage() public method

Returns the message to be displayed when the newly generated code is saved successfully.

Child classes may override this method to customize the message.

public string successMessage ( )
return string

The message to be displayed when the newly generated code is saved successfully.

                public function successMessage()
{
    return 'The controller has been generated successfully.' . $this->getLinkToTry();
}

            
validateClass() public method

Defined in: yii\gii\Generator::validateClass()

An inline validator that checks if the attribute value refers to an existing class name.

If the extends option is specified, it will also check if the class is a child class of the class represented by the extends option.

public void validateClass ( $attribute, $params )
$attribute string

The attribute being validated

$params array

The validation options

                public function validateClass($attribute, $params)
{
    $class = $this->$attribute;
    try {
        if (class_exists($class)) {
            if (isset($params['extends'])) {
                if (ltrim($class, '\\') !== ltrim($params['extends'], '\\') && !is_subclass_of($class, $params['extends'])) {
                    $this->addError($attribute, "'$class' must extend from {$params['extends']} or its child class.");
                }
            }
        } else {
            $this->addError($attribute, "Class '$class' does not exist or has syntax error.");
        }
    } catch (\Exception $e) {
        $this->addError($attribute, "Class '$class' does not exist or has syntax error.");
    }
}

            
validateMessageCategory() public method

Defined in: yii\gii\Generator::validateMessageCategory()

Checks if message category is not empty when I18N is enabled.

public void validateMessageCategory ( )

                public function validateMessageCategory()
{
    if ($this->enableI18N && empty($this->messageCategory)) {
        $this->addError('messageCategory', "Message Category cannot be blank.");
    }
}

            
validateNewClass() public method

Defined in: yii\gii\Generator::validateNewClass()

An inline validator that checks if the attribute value refers to a valid namespaced class name.

The validator will check if the directory containing the new class file exist or not.

public void validateNewClass ( $attribute, $params )
$attribute string

The attribute being validated

$params array

The validation options

                public function validateNewClass($attribute, $params)
{
    $class = ltrim($this->$attribute, '\\');
    if (($pos = strrpos($class, '\\')) === false) {
        $this->addError($attribute, "The class name must contain fully qualified namespace name.");
    } else {
        $ns = substr($class, 0, $pos);
        $path = Yii::getAlias('@' . str_replace('\\', '/', $ns), false);
        if ($path === false) {
            $this->addError($attribute, "The class namespace is invalid: $ns");
        } elseif (!is_dir($path)) {
            $this->addError($attribute, "Please make sure the directory containing this class exists: $path");
        }
    }
}

            
validateTemplate() public method

Defined in: yii\gii\Generator::validateTemplate()

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

public void validateTemplate ( )

                public function validateTemplate()
{
    $templates = $this->templates;
    if (!isset($templates[$this->template])) {
        $this->addError('template', 'Invalid template selection.');
    } else {
        $templatePath = $this->templates[$this->template];
        foreach ($this->requiredTemplates() as $template) {
            if (!is_file(Yii::getAlias($templatePath . '/' . $template))) {
                $this->addError('template', "Unable to find the required code template file '$template'.");
            }
        }
    }
}