YiiFramework入門知識點總結(jié)(圖文教程)
本文總結(jié)了YiiFramework入門知識點。分享給大家供大家參考,具體如下:
創(chuàng)建Yii應(yīng)用骨架
web為網(wǎng)站根目錄
yiic webapp /web/demo
通過GII創(chuàng)建model和CURD時需要注意
1、Model Generator 操作
即使在有表前綴的情況下,Table Name中也要填寫表的全名,即包括表前綴。如下圖:
2、Crud Generator 操作
該界面中,Model Class中填寫model名稱。首字母大寫。也可參照在生成model時,在proctected/models目錄中通過model generator生成的文件名。如下圖:
如果對news、newstype、statustype這三個表生成CURD控制器,則在Model Generator中,在Model Class中輸入:News、newsType、StatusType。大小寫與創(chuàng)建的文件名的大小寫相同。如果寫成NEWS或NeWs等都不可以。
創(chuàng)建模塊注意事項
通過GII創(chuàng)建模塊,Module ID一般用小寫。無論如何,這里填寫的ID決定main.php配置文件中的配置。如下:
'modules'=>array( 'admin'=>array(//這行的admin為Module ID。與創(chuàng)建Module時填寫的Module ID大寫寫一致 'class'=>'application.modules.admin.AdminModule',//這里的admin在windows os中大小寫無所謂,但最好與實際目錄一致。 ), ),
路由
system表示yii框架的framework目錄
application表示創(chuàng)建的應(yīng)用(比如d:\wwwroot\blog)下的protected目錄。
application.modules.Admin.AdminModule
表示應(yīng)用程序目錄(比如:d:\wwwroot\blog\protected)目錄下的modules目錄下的Admin目錄下的AdminModules.php文件(實際上指向的是該文件的類的名字)
system.db.*
表示YII框架下的framework目錄下的db目錄下的所有文件。
控制器中的accessRules說明
/** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions'=>array('index','view'),//表示任意用戶可訪問index、view方法 'users'=>array('*'),//表示任意用戶 ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions'=>array('create','update'),//表示只有認(rèn)證用戶才可操作create、update方法 'users'=>array('@'),//表示認(rèn)證用戶 ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions'=>array('admin','delete'),//表示只有用戶admin才能訪問admin、delete方法 'users'=>array('admin'),//表示指定用戶,這里指用戶:admin ), array('deny', // deny all users 'users'=>array('*'), ), ); }
看以上代碼注釋。
user: represents the user session information.詳情查閱API:CWebUser
CWebUser代表一個Web應(yīng)用程序的持久狀態(tài)。
CWebUser作為ID為user的一個應(yīng)用程序組件。因此,在任何地方都能通過Yii::app()->user 訪問用戶狀態(tài)
public function beforeSave() { if(parent::beforeSave()) { if($this->isNewRecord) { $this->password=md5($this->password); $this->create_user_id=Yii::app()->user->id;//一開始這樣寫,User::model()->user->id;(錯誤) //$this->user->id;(錯誤) $this->create_time=date('Y-m-d H:i:s'); } else { $this->update_user_id=Yii::app()->user->id; $this->update_time=date('Y-m-d H:i:s'); } return true; } else { return false; } }
getter方法或/和setter方法
<?php /** * UserIdentity represents the data needed to identity a user. * It contains the authentication method that checks if the provided * data can identity the user. */ class UserIdentity extends CUserIdentity { /** * Authenticates a user. * The example implementation makes sure if the username and password * are both 'demo'. * In practical applications, this should be changed to authenticate * against some persistent user identity storage (e.g. database). * @return boolean whether authentication succeeds. */ private $_id; public function authenticate() { $username=strtolower($this->username); $user=User::model()->find('LOWER(username)=?',array($username)); if($user===null) { $this->errorCode=self::ERROR_USERNAME_INVALID; } else { //if(!User::model()->validatePassword($this->password)) if(!$user->validatePassword($this->password)) { $this->errorCode=self::ERROR_PASSWORD_INVALID; } else { $this->_id=$user->id; $this->username=$user->username; $this->errorCode=self::ERROR_NONE; } } return $this->errorCode===self::ERROR_NONE; } public function getId() { return $this->_id; } }
model/User.php
public function beforeSave() { if(parent::beforeSave()) { if($this->isNewRecord) { $this->password=md5($this->password); $this->create_user_id=Yii::app()->user->id;//====主要為此句。得到登陸帳號的ID $this->create_time=date('Y-m-d H:i:s'); } else { $this->update_user_id=Yii::app()->user->id; $this->update_time=date('Y-m-d H:i:s'); } return true; } else { return false; } }
更多相關(guān):
/* 由于CComponent是post最頂級父類,所以添加getUrl方法。。。。如下說明: CComponent 是所有組件類的基類。 CComponent 實現(xiàn)了定義、使用屬性和事件的協(xié)議。 屬性是通過getter方法或/和setter方法定義。訪問屬性就像訪問普通的對象變量。讀取或?qū)懭雽傩詫⒄{(diào)用應(yīng)相的getter或setter方法 例如: $a=$component->text; // equivalent to $a=$component->getText(); $component->text='abc'; // equivalent to $component->setText('abc'); getter和setter方法的格式如下 // getter, defines a readable property 'text' public function getText() { ... } // setter, defines a writable property 'text' with $value to be set to the property public function setText($value) { ... } */ public function getUrl() { return Yii::app()->createUrl('post/view',array( 'id'=>$this->id, 'title'=>$this->title, )); }
模型中的rules方法
/* * rules方法:指定對模型屬性的驗證規(guī)則 * 模型實例調(diào)用validate或save方法時逐一執(zhí)行 * 驗證的必須是用戶輸入的屬性。像id,作者id等通過代碼或數(shù)據(jù)庫設(shè)定的不用出現(xiàn)在rules中。 */ /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('news_title, news_content', 'required'), array('news_title', 'length', 'max'=>128), array('news_content', 'length', 'max'=>8000), array('author_name, type_id, status_id,create_time, update_time, create_user_id, update_user_id', 'safe'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, news_title, news_content, author_name, type_id, status_id, create_time, update_time, create_user_id, update_user_id', 'safe', 'on'=>'search'), ); }
說明:
1、驗證字段必須為用戶輸入的屬性。不是由用戶輸入的內(nèi)容,無需驗證。
2、數(shù)據(jù)庫中的操作字段(即使是由系統(tǒng)生成的,比如創(chuàng)建時間,更新時間等字段——在boyLee提供的yii_computer源碼中,對系統(tǒng)生成的這些屬性沒有放在safe中。見下面代碼)。對于不是表單提供的數(shù)據(jù),只要在rules方法中沒有驗證的,都要加入到safe中,否則無法寫入數(shù)據(jù)庫。
yii_computer的News.php模型關(guān)于rules方法
/** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('news_title, news_content', 'required'), array('news_title', 'length', 'max'=>128, 'encoding'=>'utf-8'), array('news_content', 'length', 'max'=>8000, 'encoding'=>'utf-8'), array('author_name', 'length', 'max'=>10, 'encoding'=>'utf-8'), array('status_id, type_id', 'safe'), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, news_title, news_content, author_name, type_id, status_id', 'safe', 'on'=>'search'), ); }
視圖中顯示動態(tài)內(nèi)容三種方法
1、直接在視圖文件中以PHP代碼實現(xiàn)。比如顯示當(dāng)前時間,在視圖中:
2、在控制器中實現(xiàn)顯示內(nèi)容,通過render的第二個參數(shù)傳給視圖
控制器方法中包含:
$theTime=date("Y-m-d H:i:s"); $this->render('helloWorld',array('time'=>$theTime));
視圖文件:
調(diào)用的render()方法第二個參數(shù)的數(shù)據(jù)是一個array(數(shù)組類型),render()方法會提取數(shù)組中的值提供給視圖腳本,數(shù)組中的 key(鍵值)將是提供給視圖腳本的變量名。在這個例子中,數(shù)組的key(鍵值)是time,value(值)是$theTime則提取出的變量名$time是供視圖腳本使用的。這是將控制器的數(shù)據(jù)傳遞給視圖的一種方法。
3、視圖與控制器是非常緊密的兄弟,所以視圖文件中的$this指的就是渲染這個視圖的控制器。修改前面的示例,在控制器中定義一個類的公共屬性,而不是局部變量,它是值就是當(dāng)前的日期和時間。然后在視圖中通過$this訪問這個類的屬性。
視圖命名約定
視圖文件命名,請與ActionID相同。但請記住,這只是個推薦的命名約定。其實視圖文件名不必與ActionID相同,只需要將文件的名字作為第一個參數(shù)傳遞給render()就可以了。
DB相關(guān)
$Prerfp = Prerfp::model()->findAll( array( 'limit'=>'5', 'order'=>'releasetime desc' ) );
$model = Finishrfp::model()->findAll( array( 'select' => 'companyname,title,releasetime', 'order'=>'releasetime desc', 'limit' => 10 ) ); foreach($model as $val){ $noticeArr[] = " 在".$val->title."競標(biāo)中,".$val->companyname."中標(biāo)。"; }
$model = Cgnotice::model()->findAll ( array( 'select' => 'status,content,updatetime', 'condition'=> 'status = :status ', 'params' => array(':status'=>0), 'order'=>'updatetime desc', 'limit' => 10 ) ); foreach($model as $val){ $noticeArr[] = $val->content; }
$user=User::model()->find('LOWER(username)=?',array($username));
$noticetype = Dictionary::model()->find(array( 'condition' => '`type` = "noticetype"') );
// 查找postID=10 的那一行 $post=Post::model()->find('postID=:postID', array(':postID'=>10));
也可以使用$condition 指定更復(fù)雜的查詢條件。不使用字符串,我們可以讓$condition 成為一個CDbCriteria 的實例,它允許我們指定不限于WHERE 的條件。例如:
$criteria=new CDbCriteria; $criteria->select='title'; // 只選擇'title' 列 $criteria->condition='postID=:postID'; $criteria->params=array(':postID'=>10); $post=Post::model()->find($criteria); // $params 不需要了
注意,當(dāng)使用CDbCriteria 作為查詢條件時,$params 參數(shù)不再需要了,因為它可以在CDbCriteria 中指定,就像上面那樣。
一種替代CDbCriteria 的方法是給find 方法傳遞一個數(shù)組。數(shù)組的鍵和值各自對應(yīng)標(biāo)準(zhǔn)(criterion)的屬性名和值,上面的例子可以重寫為如下:
$post=Post::model()->find(array( 'select'=>'title', 'condition'=>'postID=:postID', 'params'=>array(':postID'=>10), ));
其它
1、鏈接
具體查找API文檔:CHtml的link()方法
具體請查找API文檔:CController的createUrl()方法
以上兩個連接效果等同
組件包含
一個示例:
在視圖中底部有如下代碼:
打開protected/components下的Notice.php文件,內(nèi)容如下:
<?php Yii::import('zii.widgets.CPortlet'); class Banner extends CPortlet { protected function renderContent() { $this->render('banner'); } }
渲染的視圖banner,是在protected/components/views目錄下。
具體查看API,關(guān)鍵字:CPortlet
獲取當(dāng)前host
Yii::app()->request->getServerName(); //and $_SERVER['HTTP_HOST']; $url = 'http://'.Yii::app()->request->getServerName(); $url .= CController::createUrl('user/activateEmail', array('emailActivationKey'=>$activationKey)); echo $url;
關(guān)于在發(fā)布新聞時添加ckeditor擴(kuò)展中遇到的情況
$this->widget('application.extensions.editor.CKkceditor',array( "model"=>$model, # Data-Model "attribute"=>'news_content', # Attribute in the Data-Model "height"=>'300px', "width"=>'80%', "filespath"=>Yii::app()->basePath."/../up/", "filesurl"=>Yii::app()->baseUrl."/up/", );
echo Yii::app()->basePath
如果項目目錄在:d:\wwwroot\blog目錄下。則上面的值為d:\wwwroot\blog\protected。注意路徑最后沒有返斜杠。
echo Yii::app()->baseUrl;
如果項目目錄在:d:\wwwroot\blog目錄下。則上面的值為/blog。注意路徑最后沒有返斜杠。
(d:\wwwroot為網(wǎng)站根目錄),注意上面兩個區(qū)別。一個是basePath,一個是baseUrl
其它(不一定正確)
在一個控制器A對應(yīng)的A視圖中,調(diào)用B模型中的方法,采用:B::model()->B模型中的方法名();
前期需要掌握的一些API
CHtml
希望本文所述對大家基于Yii框架的PHP程序設(shè)計有所幫助。
- 記錄Yii2框架開發(fā)微信公眾號遇到的問題及解決方法
- 使用YII2框架實現(xiàn)微信公眾號中表單提交功能
- 完美利用Yii2微信后臺開發(fā)的系列總結(jié)
- Yii PHP Framework實用入門教程(詳細(xì)介紹)
- YII Framework框架使用YIIC快速創(chuàng)建YII應(yīng)用之migrate用法實例詳解
- YII Framework框架教程之使用YIIC快速創(chuàng)建YII應(yīng)用詳解
- Yii Framework框架獲取分類下面的所有子類方法
- YII Framework框架教程之緩存用法詳解
- YII Framework框架教程之國際化實現(xiàn)方法
- YII Framework框架教程之安全方案詳解
- Yii Framework框架開發(fā)微信公眾平臺示例
相關(guān)文章
PHP+jQuery+Ajax實現(xiàn)用戶登錄與退出
本文使用Ajax無刷新登錄和退出,從而提升了用戶體驗。 若用戶為登錄狀態(tài),則顯示用戶相關(guān)登錄信息,否則顯示登錄表單。2015-04-04Symfony2框架創(chuàng)建項目與模板設(shè)置實例詳解
這篇文章主要介紹了Symfony2框架創(chuàng)建項目與模板設(shè)置的方法,結(jié)合實例形式詳細(xì)分析了Symfony2框架的具體步驟與詳細(xì)實現(xiàn)代碼,需要的朋友可以參考下2016-03-03使用PHP+AJAX讓W(xué)ordPress動態(tài)加載文章的教程
這篇文章主要介紹了使用PHP+AJAX讓W(xué)ordPress動態(tài)加載文章的教程,即不用手動刷新瀏覽器頁面即可讓加載好的文章顯示,需要的朋友可以參考下2015-12-12