程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> YiiFramework入門知識點總結(圖文教程)

YiiFramework入門知識點總結(圖文教程)

編輯:PHP綜合

本文總結了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 property
public 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文件,內容如下:

<?php
Yii::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程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved