Yii框架官方指南系列41-專題:自動程式碼生成
自版本 1.1.2 起, Yii 裝備了基於 Web 介面的程式碼產生工具Gii。 它取代了先前的命令列端的程式碼產生工具 yiic shell
。 在這部分,我們將講解如何使用 Gii 以及如何擴展 Gii 以增加我們的開發成果。
1. 使用 Gii
Gii 是以模組的方式實現的,它必須在一個已存在的 Yii 應用程式中使用。要使用 Gii,我們首先更改應用程式的設定如下:
return array( ...... 'modules'=>array( 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'在这里填写密码', // 'ipFilters'=>array(...IP 列表...), // 'newFileMode'=>0666, // 'newDirMode'=>0777, ), ), );
在上面,我們聲明了一個名為 gii
的模組,它的類別是 GiiModule。我們也為這個模組設定了一個密碼,我們訪問 Gii 時會有一個輸入框要求填寫這個密碼。
出於安全考慮,預設只允許本機存取 Gii。若允許其他可信賴的機器存取它,我們需要如上所示配置GiiModule::ipFilters 屬性。
因為 Gii 會產生並保存新檔案到應用程式中,我們需要確保 Web 伺服器進程有權限這樣做。上面的GiiModule::newFileMode 和 GiiModule::newDirMode 屬性控制如何產生新檔案和新目錄。
注意: Gii 主要用作一個開發工具。因此,應當只在開發機器上安裝它。因為它可以在應用程式中產生新的 PHP 文件,我們應該對安全問題足夠重視(例如設定密碼,IP 過濾)。
現在可以透過 URL http://www.php.cn/
存取 Gii 了。這裡我們假設http://www.php.cn/
是存取 Yii 應用程式的 URL。
若 Yii 應用程式使用 path
格式的 URL (查看 URL management),我們可以透過 URL http://www.php.cn/
存取 Gii。 我們可能需要增加以下 URL 規則到已有的 URL 規則的前面:
'components'=>array( ...... 'urlManager'=>array( 'urlFormat'=>'path', 'rules'=>array( 'gii'=>'gii', 'gii/<controller:\w+>'=>'gii/<controller>', 'gii/<controller:\w+>/<action:\w+>'=>'gii/<controller>/<action>', ...已有的规则... ), ), )
Gii 有一些預設的程式碼產生器。每個代碼產生器負責產生特定類型的代碼。例如 controller 生成器產生一個 controller 類別以及一些 action view 腳本;model 生成器為指定的資料表產生一個 ActiveRecord 類別。
使用一個產生器的基本流程如下:
進入產生器頁面;
填入指定程式碼產生參數的輸入框。例如,使用 Module Generator 建立新模組,你需要指定 module ID;
點擊
Preview
按鈕預覽即將產生的程式碼。你將看到一個表格中列出了將要產生的文件清單。你可以點選其中任何一個檔案來預覽程式碼;點擊
Generate
按鈕來產生這些程式碼檔案;查看程式碼產生日誌。
2. 擴展 Gii
雖然默認的 Gii 代碼生成器可以生成非常強大的代碼,然而我們經常想定制它們或者創建一個新的來適應我們的口味和需求。例如,我們想要讓產生的程式碼是我們喜歡的風格,或是想讓程式碼支援多種語言。所有這些在 Gii 中都可非常容易實現。
可以 2 種方式擴充 Gii:客製化已存在的程式碼產生器的程式碼模板,以及編寫新的程式碼產生器。
程式碼產生器的架構
一個代碼產生器儲存在一個目錄中,這個目錄的名字被認為是生成器的名字。目錄通常由下列內容組成:
model/ the model generator root folder ModelCode.php the code model used to generate code ModelGenerator.php the code generation controller views/ containing view scripts for the generator index.php the default view script templates/ containing code template sets default/ the 'default' code template set model.php the code template for generating model class code
產生器搜尋路徑
Gii 在GiiModule::generatorPaths 屬性指定的目錄中尋找可用的產生器。 當需要客製化時,我們可以在應用程式的設定檔中做以下配置,
return array( 'modules'=>array( 'gii'=>array( 'class'=>'system.gii.GiiModule', 'generatorPaths'=>array( 'application.gii', // a path alias ), ), ), );
上面的設定告訴Gii 在別名是 application.gii
的目錄中尋找生成器,以及預設的位置system.gii.generators
。
在不同的搜尋路徑有同名的生成器也是可以的。這種情況下,在 GiiModule::generatorPaths 指定目錄中先出現的產生器有優先權。
定製程式碼範本
這是擴充 Gii 最容易最常用的方式。我們使用一個例子來介紹如何定製程式碼模板。假設我們想要自訂由 model 生成器產生的程式碼。
我們先建立一個名為 protected/gii/model/templates/compact
的目錄。這裡的 model
代表我們將要override 預設的 model 產生器。 templates/compact
意味著我們將增加一個新的程式碼模板集名為 compact
。
接著我們在應用程式設定裡把 application.gii
增加到 GiiModule::generatorPaths 。如上所示。
现在打开 model 代码生成器页面。点击 Code Template
输入框。我们应当看到一个下拉列表,这个列表包含了我们新建的模板目录 compact
。可是,若我们选择此模板生成代码,我们将看到错误。这是因为我们还没有在新的 compact
模板集中放入任何实际的代码模板文件。
复制文件 framework/gii/generators/model/templates/default/model.php
到protected/gii/model/templates/compact
。若我们再次尝试以 compact
模板生成,我们会成功。但是,生成的代码和以 default
模板集生成的代码没什么不同。
现在是时候做点真正的工作了。打开文件 protected/gii/model/templates/compact/model.php
以编辑它。记得这个文件将作为类似一个视图文件被使用,意味着它可以包含 PHP 表达式和语句。让我们更改模板以便生成的代码里 attributeLabels()
方法使用 Yii::t()
来翻译属性标签:
public function attributeLabels() { return array( <?php foreach($labels as $name=>$label): ?> <?php echo "'$name' => Yii::t('application', '$label'),\n"; ?> <?php endforeach; ?> ); }
在每个代码模板中,我们可以访问一些预定义的变量,例如上面例子中的 $labels
。这些变量由对应的代码生成器提供。不同的代码生成器可能在他们的代码模板中提供不同的变量。请认真阅读默认代码模板中的描述。
创建新的生成器
In this sub-section, we show how to create a new generator that can generate a new widget class.
We first create a directory named protected/gii/widget
. Under this directory, we will create the following files:
WidgetGenerator.php
: contains theWidgetGenerator
controller class. This is the entry point of the widget generator.WidgetCode.php
: contains theWidgetCode
model class. This class has the main logic for code generation.views/index.php
: the view script showing the code generator input form.templates/default/widget.php
: the default code template for generating a widget class file.
Creating WidgetGenerator.php
The WidgetGenerator.php
file is extremely simple. It only contains the following code:
class WidgetGenerator extends CCodeGenerator { public $codeModel='application.gii.widget.WidgetCode'; }
In the above code, we specify that the generator will use the model class whose path alias isapplication.gii.widget.WidgetCode
. The WidgetGenerator
class extends from CCodeGenerator which implements a lot of functionalities, including the controller actions needed to coordinate the code generation process.
Creating WidgetCode.php
The WidgetCode.php
file contains the WidgetCode
model class that has the main logic for generating a widget class based on the user input. In this example, we assume that the only input we want from the user is the widget class name. Our WidgetCode
looks like the following:
class WidgetCode extends CCodeModel { public $className; public function rules() { return array_merge(parent::rules(), array( array('className', 'required'), array('className', 'match', 'pattern'=>'/^\w+$/'), )); } public function attributeLabels() { return array_merge(parent::attributeLabels(), array( 'className'=>'Widget Class Name', )); } public function prepare() { $path=Yii::getPathOfAlias('application.components.' . $this->className) . '.php'; $code=$this->render($this->templatepath.'/widget.php'); $this->files[]=new CCodeFile($path, $code); } }
The WidgetCode
class extends from CCodeModel. Like a normal model class, in this class we can declarerules()
and attributeLabels()
to validate user inputs and provide attribute labels, respectively. Note that because the base class CCodeModel already defines some rules and attribute labels, we should merge them with our new rules and labels here.
The prepare()
method prepares the code to be generated. Its main task is to prepare a list of CCodeFileobjects, each of which represent a code file being generated. In our example, we only need to create oneCCodeFile object that represents the widget class file being generated. The new widget class will be generated under the protected/components
directory. We call CCodeFile::render method to generate the actual code. This method includes the code template as a PHP script and returns the echoed content as the generated code.
Creating views/index.php
Having the controller (WidgetGenerator
) and the model (WidgetCode
), it is time for us to create the viewviews/index.php
.
<h1>Widget Generator</h1> <?php $form=$this->beginWidget('CCodeForm', array('model'=>$model)); ?> <p class="row"> <?php echo $form->labelEx($model,'className'); ?> <?php echo $form->textField($model,'className',array('size'=>65)); ?> <p class="tooltip"> Widget class name must only contain word characters. </p> <?php echo $form->error($model,'className'); ?> </p> <?php $this->endWidget(); ?>
In the above, we mainly display a form using the CCodeForm widget. In this form, we display the field to collect the input for the className
attribute in WidgetCode
.
When creating the form, we can exploit two nice features provided by the CCodeForm widget. One is about input tooltips. The other is about sticky inputs.
If you have tried any default code generator, you will notice that when setting focus in one input field, a nice tooltip will show up next to the field. This can easily achieved here by writing next to the input field a p
whose CSS class is tooltip
.
For some input fields, we may want to remember their last valid values so that the user can save the trouble of re-entering them each time they use the generator to generate code. An example is the input field collecting the controller base class name default controller generator. These sticky fields are initially displayed as highlighted static text. If we click on them, they will turn into input fields to take user inputs.
In order to declare an input field to be sticky, we need to do two things.
First, we need to declare a sticky
validation rule for the corresponding model attribute. For example, the default controller generator has the following rule to declare that baseClass
and actions
attributes are sticky:
public function rules() { return array_merge(parent::rules(), array( ...... array('baseClass, actions', 'sticky'), )); }
Second, we need to add a CSS class named sticky
to the container p
of the input field in the view, like the following:
<p class="row sticky"> ...input field here... </p>
Creating templates/default/widget.php
Finally, we create the code template templates/default/widget.php
. As we described earlier, this is used like a view script that can contain PHP expressions and statements. In a code template, we can always access the $this
variable which refers to the code model object. In our example, $this
refers to the WidgetModel
object. We can thus get the user-entered widget class name via $this->className
.
<?php echo '<?php'; ?> class <?php echo $this->className; ?> extends CWidget { public function run() { } }
This concludes the creation of a new code generator. We can access this code generator immediately via the URL http://www.php.cn
以上就是Yii框架官方指南系列41——专题:自动代码生成的内容,更多相关内容请关注PHP中文网(www.php.cn)!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Yii是一款基於PHP的高效能MVC框架,它提供了非常豐富的工具和功能,支援快速、有效率地開發Web應用程式。其中,Yii框架的RESTfulAPI功能得到了越來越多開發者的關注和喜愛,因為使用Yii框架可以非常方便地構建出高性能、易擴展的RESTful接口,為Web應用的開發提供了強有力的支持。 RESTfulAPI簡介RESTfulAPI是一種基於

Yii框架中間件:為應用程式提供多重資料儲存支援介紹中間件(middleware)是Yii框架中的重要概念,它為應用程式提供了多重資料儲存支援。中間件的作用類似於一個過濾器,它能夠在應用程式的請求和回應之間插入自訂程式碼。透過中間件,我們可以對請求進行處理、驗證、過濾,然後將處理後的結果傳遞給下一個中間件或最終的處理程序。 Yii框架中的中間件使用起來非常

近年來,隨著遊戲產業的快速發展,越來越多的玩家開始尋找遊戲攻略來幫助遊戲過關。因此,創建遊戲攻略網站可以讓玩家更方便取得遊戲攻略,同時也能為玩家提供更好的遊戲體驗。在創建這樣一個網站時,我們可以使用Yii框架來進行開發。 Yii框架是一個基於PHP程式語言的Web應用開發框架。它具有高效、安全、擴展性強等特點,可以為我們更快速、高效地創建一個遊戲攻略

使用Yii框架實現網頁快取和頁面分塊的步驟引言:在Web開發過程中,為了提升網站的效能和使用者體驗,常常需要對頁面進行快取和分塊處理。 Yii框架提供了強大的快取和佈局功能,可以幫助開發者快速實現網頁快取和頁面分塊,本文將介紹如何使用Yii框架進行網頁快取和頁面分塊的實作。一、網頁快取開啟網頁快取在Yii框架中,可以透過設定檔來開啟網頁快取。開啟主設定檔co

隨著Web應用程式的快速發展,現代Web開發已成為一項重要技能。許多框架和工具可用於開發高效的Web應用程序,其中Yii框架就是一個非常流行的框架。 Yii是一個高效能、基於元件的PHP框架,它採用了最新的設計模式和技術,提供了強大的工具和元件,是建立複雜Web應用程式的理想選擇。在本文中,我們將討論如何使用Yii框架來建立Web應用程式。安裝Yii框架首先,

Yii框架中間件:為應用程式新增日誌記錄和偵錯功能【引言】在開發Web應用程式時,我們通常需要添加一些附加功能以提高應用程式的效能和穩定性。 Yii框架提供了中間件的概念,使我們能夠在應用程式處理請求之前和之後執行一些額外的任務。本文將介紹如何使用Yii框架的中間件功能來實作日誌記錄和除錯功能。 【什麼是中間件】中間件是指在應用程式處理請求之前和之後,對請求和回應做

在Yii框架中,控制器(Controllers)扮演著處理請求的重要角色。除了處理常規的頁面請求之外,控制器還可以用於處理Ajax請求。本文將介紹在Yii框架中處理Ajax請求的方法,並提供程式碼範例。在Yii框架中,處理Ajax請求可以透過以下步驟進行:第一步,建立一個控制器(Controller)類別。可以透過繼承Yii框架提供的基礎控制器類別yiiwebCo

在現代的Web應用程式開發中,調試工具是不可或缺的。它們可以幫助開發者找到和解決應用程式的各種問題。 Yii框架作為一款流行的Web應用程式框架,自然也提供了一些除錯工具。本文將重點介紹Yii框架中的調試工具,並討論它們如何幫助我們分析和調試應用程式。 GiiGii是Yii框架的程式碼產生器。它可以自動產生Yii應用程式的程式碼,如模型、控制器和視圖等。使用Gii,
