YiiFramework入門知識點總結(圖文教程)_php執行個體

來源:互聯網
上載者:User

本文總結了YiiFramework入門知識點。分享給大家供大家參考,具體如下:

建立Yii應用骨架

web為網站根目錄
yiic webapp /web/demo

通過GII建立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。大小寫與建立的檔案名稱的大小寫相同。如果寫成NEWS或NeWs等都不可以。

建立模組注意事項

通過GII建立模組,Module ID一般用小寫。無論如何,這裡填寫的ID決定main.php設定檔中的配置。如下:

'modules'=>array(  'admin'=>array(//這行的admin為Module ID。與建立Module時填寫的Module ID大寫寫一致    'class'=>'application.modules.admin.AdminModule',//這裡的admin在windows os中大小寫無所謂,但最好與實際目錄一致。  ),),

路由

system表示yii架構的framework目錄
application表示建立的應用(比如d:\wwwroot\blog)下的protected目錄。
application.modules.Admin.AdminModule
表示應用程式目錄(比如: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'),//表示只有認證使用者才可操作create、update方法      'users'=>array('@'),//表示認證使用者    ),    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應用程式的持久狀態。
CWebUser作為ID為user的一個應用程式組件。因此,在任何地方都能通過Yii::app()->user 訪問使用者狀態

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;  }}

更多相關:

/*由於CComponent是post最頂級父類,所以添加getUrl方法。。。。如下說明:CComponent 是所有組件類的基類。CComponent 實現了定義、使用屬性和事件的協議。屬性是通過getter方法或/和setter方法定義。訪問屬性就像訪問普通的物件變數。讀取或寫入屬性將調用應相的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 propertypublic function setText($value) { ... }*/public function getUrl(){  return Yii::app()->createUrl('post/view',array(    'id'=>$this->id,    'title'=>$this->title,  ));}

模型中的rules方法

/* * rules方法:指定對模型屬性的驗證規則 * 模型執行個體調用validate或save方法時逐一執行 * 驗證的必須是使用者輸入的屬性。像id,作者id等通過代碼或資料庫設定的不用出現在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、驗證欄位必須為使用者輸入的屬性。不是由使用者輸入的內容,無需驗證。
2、資料庫中的操作欄位(即使是由系統產生的,比如建立時間,更新時間等欄位——在boyLee提供的yii_computer源碼中,對系統產生的這些屬性沒有放在safe中。見下面代碼)。對於不是表單提供的資料,只要在rules方法中沒有驗證的,都要加入到safe中,否則無法寫入資料庫

yii_computer的News.php模型關於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'),  );}

視圖中顯示動態內容三種方法

1、直接在視圖檔案中以PHP代碼實現。比如顯示目前時間,在視圖中:

複製代碼 代碼如下:
<?php echo date("Y-m-d H:i:s");?>

2、在控制器中實現顯示內容,通過render的第二個參數傳給視圖

控制器方法中包含:

$theTime=date("Y-m-d H:i:s");$this->render('helloWorld',array('time'=>$theTime));

視圖檔案:

複製代碼 代碼如下:
<?php echo $time;?>

調用的render()方法第二個參數的資料是一個array(數群組類型),render()方法會提取數組中的值提供給視圖指令碼,數組中的 key(索引值)將是提供給視圖指令碼的變數名。在這個例子中,數組的key(索引值)是time,value(值)是$theTime則提取出的變數名$time是供視圖指令碼使用的。這是將控制器的資料傳遞給視圖的一種方法。

3、視圖與控制器是非常緊密的兄弟,所以視圖檔案中的$this指的就是渲染這個視圖的控制器。修改前面的樣本,在控制器中定義一個類的公用屬性,而不是局部變數,它是值就是當前的日期和時間。然後在視圖中通過$this訪問這個類的屬性。

視圖命名規範

視圖檔案命名,請與ActionID相同。但請記住,這隻是個推薦的命名規範。其實視圖檔案名稱不必與ActionID相同,只需要將檔案的名字作為第一個參數傳遞給render()就可以了。

DB相關

$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."競標中,".$val->companyname."中標。";}
$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 指定更複雜的查詢條件。不使用字串,我們可以讓$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 不需要了

注意,當使用CDbCriteria 作為查詢條件時,$params 參數不再需要了,因為它可以在CDbCriteria 中指定,就像上面那樣。

一種替代CDbCriteria 的方法是給find 方法傳遞一個數組。數組的鍵和值各自對應標準(criterion)的屬性名稱和值,上面的例子可以重寫為如下:

$post=Post::model()->find(array( 'select'=>'title', 'condition'=>'postID=:postID', 'params'=>array(':postID'=>10),));

其它

1、連結

複製代碼 代碼如下:
<span class="tt"><?php echo CHtml::link(Controller::utf8_substr($val->title,0,26),array('prerfp/details','id'=>$val->rfpid),array('target'=>'_blank'));?></a> </span>

具體尋找API文檔:CHtml的link()方法

複製代碼 代碼如下:
<span class="tt"><a target="_blank"  title="<?php echo $val->title;?>" href="<?php echo $this->createUrl('prerfp/details',array('id'=>$val->rfpid)) ;?>" ><?php echo Controller::utf8_substr($val->title,0,26); ?></a> </span>

具體請尋找API文檔:CController的createUrl()方法

以上兩個串連效果等同

組件包含

一個樣本:

在視圖中底部有如下代碼:

複製代碼 代碼如下:
<?php $this->widget ( 'Notice' ); ?>

開啟protected/components下的Notice.php檔案,內容如下:

<?phpYii::import('zii.widgets.CPortlet');class Banner extends CPortlet{  protected function renderContent()  {    $this->render('banner');  }}

渲染的視圖banner,是在protected/components/views目錄下。

具體查看API,關鍵字:CPortlet

擷取當前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;

關於在發布新聞時添加ckeditor擴充中遇到的情況

$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為網站根目錄),注意上面兩個區別。一個是basePath,一個是baseUrl

其它(不一定正確)

在一個控制器A對應的A視圖中,調用B模型中的方法,採用:B::model()->B模型中的方法名();

前期需要掌握的一些API
CHtml

希望本文所述對大家基於Yii架構的PHP程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.