首頁  >  文章  >  後端開發  >  PHP中Yii框架的基本用法

PHP中Yii框架的基本用法

墨辰丷
墨辰丷原創
2018-06-07 14:34:113863瀏覽

這篇文章主要介紹PHPYii框架的基本用法,有興趣的朋友參考下,希望對大家有幫助。

在 Yii 自動產生的程式碼裡,我們總是能在 admin 的介面看到 CGridView 的身影。這是一個很好用的展示資料的表格控件,用的好可以明顯地加快開發進度。下面就讓我們來探索 CGridView 的基本使用:

drop table if exists `tbl_user`; 
CREATE TABLE tbl_user 
( 
  `user_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键', 
  `username` VARCHAR(128) NOT NULL comment '用户名', 
  `nickname` VARCHAR(128) NOT NULL comment '昵称', 
  `password` VARCHAR(128) NOT NULL comment '密码', 
  `email` VARCHAR(128) NOT NULL comment '邮箱', 
  `is_delete` tinyint not null default 0 comment '删除标志', 
  unique key(`username`), 
  primary key (`user_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='用户表'; 
 
drop table if exists `tbl_post`; 
CREATE TABLE tbl_post 
( 
  `post_id` INTEGER NOT NULL AUTO_INCREMENT comment '主键', 
  `title` VARCHAR(128) NOT NULL comment '标题', 
  `content` TEXT NOT NULL comment '文章内容', 
  `tags` TEXT comment '标签', 
  `status` INTEGER NOT NULL comment '状态,0 = 草稿,1 = 审核通过,-1 = 审核不通过,2 = 发布', 
  `create_time` INTEGER comment '创建时间', 
  `update_time` INTEGER comment '更新时间', 
  `author_id` INTEGER NOT NULL comment '作者', 
  `is_delete` tinyint not null default 0 comment '删除标志', 
  CONSTRAINT `post_ibfk_1` FOREIGN KEY (author_id) 
    REFERENCES tbl_user (`user_id`) ON DELETE CASCADE ON UPDATE RESTRICT, 
  primary key (`post_id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 comment='日志表';

    兩個表一個儲存作者資訊一個儲存日誌,其中日誌有一個外鍵關聯到 user。兩個表裡面的 is_delete 欄位是標誌該筆記錄是否被刪除,0 為未刪除,1 為已刪除。讓我們來看看用 gii 產生的 Post 類別的 relation 方法:

/** 
 * @return array relational rules. 
 */ 
public function relations() 
{ 
  // NOTE: you may need to adjust the relation name and the related 
  // class name for the relations automatically generated below. 
  return array( 
    'comments' => array(self::HAS_MANY, 'Comment', 'post_id'), 
    'author' => array(self::BELONGS_TO, 'User', 'author_id'), 
  ); 
}

    其中的 author 外鍵作為 BELONGS_TO 關係存在,符合我們的預期。
    說了這麼多,看看自動產生的 Post 中 admin.php 裡 CGridView 的程式碼吧:

<?php $this->widget(&#39;zii.widgets.grid.CGridView&#39;, array( 
  &#39;id&#39;=>&#39;post-grid&#39;, 
  &#39;dataProvider&#39;=>$model->search(), 
  &#39;filter&#39;=>$model, 
  &#39;columns&#39;=>array( 
    &#39;post_id&#39;, 
    &#39;title&#39;, 
    &#39;content&#39;, 
    &#39;tags&#39;, 
    &#39;status&#39;, 
    &#39;create_time&#39;, 
    &#39;update_time&#39;, 
    &#39;author_id&#39;, 
    &#39;is_delete&#39;, 
    array( 
      &#39;class&#39;=>&#39;CButtonColumn&#39;, 
    ), 
  ), 
)); ?>

    看!雖然我們什麼都沒寫,但這就是這個控制的最基礎使用了。 dataProvider 是由model 裡面的search 函數提供的數據,filter...暫時看不出這裡的作用,columns 控制展示的每一列,其中最後一項的CButtonColumn 向我們展示了三個按鈕,分別是查看  更新和刪除。
    接下來我們一點點地改造.

用CGridView 展示我們真正要的資料形式:    很多時候,資料庫裡的東西不適合直接展示給使用者看,需要我們進行一定的處理之後才適合閱讀。但這裡不經過修改的話 CGridView 只會把資料庫的值原封不動地呈現,所以,我們應該在對應的欄位進行修改。例如 is_delete 字段,資料庫裡存放的是 0 和 1,但是在這裡閱讀就不太好了,我們應該改成 1 展示 '是' ,0展示 '否'。看看下面的程式碼,我們用了一個array,兩個鍵分別是name 和value,name 對應的要填寫該model 擁有的字段,而value 是你想展示的數據,這裡可以寫成一個php 語句,作為可以執行的程式碼。看到這裡,是不是覺得對這個 value 我們可以做很多事?有的同學可能要問,如果我想執行的程式碼很長,難道都寫在 value 裡面? 。 。 。我說同學,你不會在其他地方寫成一個函數然後在這裡呼叫它嗎? ?

<?php $this->widget(&#39;zii.widgets.grid.CGridView&#39;, array( 
  &#39;id&#39;=>&#39;post-grid&#39;, 
  &#39;dataProvider&#39;=>$model->search(), 
  &#39;filter&#39;=>$model, 
  &#39;columns&#39;=>array( 
    &#39;post_id&#39;, 
    &#39;title&#39;, 
    &#39;content&#39;, 
    &#39;tags&#39;, 
    &#39;status&#39;, 
    &#39;create_time&#39;, 
    &#39;update_time&#39;, 
    &#39;author_id&#39;, 
    &#39;is_delete&#39;, 
    array( 
      &#39;name&#39;=>&#39;is_delete&#39;, 
      &#39;value&#39;=>&#39;is_delete?"是":"否"&#39; //value 是可以执行 php 语句的哦 
    ) 
    array( 
      &#39;class&#39;=>&#39;CButtonColumn&#39;, 
    ), 
  ), 
)); ?>

     除此之外,還有一些常用的選項,都可以在array 裡面填寫,下面是比較常見的使用方式(其他部分程式碼省略):

array( 
  &#39;name&#39;=>&#39;is_delete&#39;, 
  &#39;value&#39;=>&#39;is_delete?"是":"否"&#39; //value 是可以执行 php 语句的哦 
  &#39;filter&#39; => array(0=>&#39;否&#39;,1=>&#39;是&#39;), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单 
  &#39;htmlOptions&#39;=>array(&#39;class&#39;=>&#39;delete&#39;), //可以定义 html 选项,这里是定义了带一个 delete 的类 
),

     上面我們用name 的話那是model 裡原來就有的字段,如果我們想展示自己定義的新內容呢,用header :

array( 
  &#39;header&#39;=>&#39;备注&#39;, 
  &#39;value&#39;=> &#39;display your data&#39; 
),

添加CCheckBoxColumn :    有時也許我們會需要一個複選框框,來對每一行進行選擇,這時,我們可以增加一列,用CCheckBoxColumn 類別:

<?php $this->widget(&#39;zii.widgets.grid.CGridView&#39;, array( 
  &#39;id&#39;=>&#39;post-grid&#39;, 
  &#39;dataProvider&#39;=>$model->search(), 
  &#39;filter&#39;=>$model, 
  &#39;columns&#39;=>array( 
    array( 
      &#39;selectableRows&#39; => 2, //允许多选,改为 0 时代表不允许修改,1 的话为单选 
      &#39;class&#39; => &#39;CCheckBoxColumn&#39;,//复选框 
      &#39;headerHtmlOptions&#39; => array(&#39;width&#39;=>&#39;18px&#39;),//头部的 html 选项 
      &#39;checkBoxHtmlOptions&#39; => array(&#39;name&#39; => &#39;myname&#39;,&#39;class&#39;=>&#39;myclass&#39;), //复选框的 html 选项 
    ), 
    &#39;post_id&#39;, 
    &#39;title&#39;, 
    &#39;content&#39;, 
    &#39;tags&#39;, 
    &#39;status&#39;, 
    &#39;create_time&#39;, 
    &#39;update_time&#39;, 
    &#39;author_id&#39;, 
    &#39;is_delete&#39;, 
    array( 
      &#39;name&#39;=>&#39;is_delete&#39;, 
      &#39;value&#39;=>&#39;is_delete?"是":"否"&#39;, //value 是可以执行 php 语句的哦 
      &#39;filter&#39; => array(0=>&#39;否&#39;,1=>&#39;是&#39;), //自己定义搜索过滤的方式,这里为 是 和 否 的下拉菜单 
      &#39;htmlOptions&#39;=>array(&#39;class&#39;=>&#39;delete&#39;), //可以定义 html 选项,这里是定义了带一个 delete 的类 
    ), 
    array( 
      &#39;class&#39;=>&#39;CButtonColumn&#39;, 
    ), 
  ), 
));

修改ButtonColumn:   注意到清單每一項的最後三個小圖示嗎?不需要的話當然是直接刪了,那要是只要其中某幾個呢?可以加一個template 參數:

array( 
     &#39;class&#39;=>&#39;ButtonColumn&#39;, 
     &#39;template&#39;=>"{view} {update}", 
   ),

    也可以自訂按鈕:

array( 
  &#39;class&#39;=>&#39;ButtonColumn&#39;, 
  &#39;template&#39;=>"{view} {update} {print}", 
  &#39;buttons&#39;=>array( 
      &#39;print&#39;=>array( 
          &#39;label&#39;=>&#39;打印&#39;, 
          &#39;url&#39;=>&#39;Yii::app()->controller->createUrl("print", array("id"=>$data->post_id))&#39;, 
          &#39;options&#39;=>array("target"=>"_blank"), 
        ), 
      ), 
    ),

刷新時觸發Javascript:     如果你想在每次搜尋之後觸發一些Javascript ,Yii也提供了這個選項,你只要寫成一個函數然後設定afterAjaxUpdate 就好,記住這只是在ajax 請求完成之後調用的,如果你想在頁面一開始加載完成就調用的話需要另外加到頁面的  Javascript

  $js = <<<_JS_ 
function(){ 
  alert(&#39;The ajax finish&#39;); 
 
} 
_JS_; 
 
$this->widget(&#39;zii.widgets.grid.CGridView&#39;, array( 
  &#39;id&#39;=>&#39;post-grid&#39;, 
  &#39;dataProvider&#39;=>$model->search(), 
  &#39;filter&#39;=>$model, 
  &#39;afterAjaxUpdate&#39;=>$js, //看这里,ajax 之后调用的 javascript 在这里.... 
  &#39;columns&#39;=>array( 
    array( 
      &#39;selectableRows&#39; => 2, //允许多选,改为 0 时代表不允许修改,1 的话为单选 
      &#39;class&#39; => &#39;CCheckBoxColumn&#39;,//复选框 
      &#39;headerHtmlOptions&#39; => array(&#39;width&#39;=>&#39;18px&#39;), 
      &#39;checkBoxHtmlOptions&#39; => array(&#39;name&#39; => &#39;myname&#39;,&#39;class&#39;=>&#39;myclass&#39;), 
    ), 
    ....

 新增關聯表相關欄位的搜尋:     先說一句,我們在這裡只談」一對多「 的關聯搜索,首先,不要忘了我們的資料庫,忘記的同學請戳這裡:這裡,可以看到在tbl_post 中是有一個外鍵關聯到tbl_user 表的,用以查找作者的相關資訊。建造了資料庫之後,看看我們產生的Yii 程式碼的POST 的Model, 裡面的realtion 如下(忽略comment 的):

/** 
 * @return array relational rules. 
 */ 
public function relations() 
{ 
  // NOTE: you may need to adjust the relation name and the related 
  // class name for the relations automatically generated below. 
  return array( 
    &#39;comments&#39; => array(self::HAS_MANY, &#39;Comment&#39;, &#39;post_id&#39;), 
    &#39;author&#39; => array(self::BELONGS_TO, &#39;User&#39;, &#39;author_id&#39;), 
  ); 
}

    可以看到POST 和USER 表可以透過author 鍵進行訪問,例如: $model->author->nickname,而且這裡是BELONGS_TO 關係。
    說了這麼多,我們的需求到底是什麼? ....

     產品經理推了一下眼鏡:」我們要在日誌的後台管理介面加一個功能,可以透過作者名稱搜尋到對應的文章。這個比較急,今晚就要完成。 「

    淡定淡定,不就是改需求吗。忽略进度要求,我们研究一下究竟要做什么。
    其实很简单的,不就是在 POST 的 admin 界面中增加一列作者名称,然后可以通过作者名的 模糊搜索 去找到对应日志吗?看看代码,要是通过 作者 id 去搜索不就简单了吗?不过这样确实不太友好...如果是展示作者名字而已不也是很简单吗?加一个 header 然后 value 是 $data->author->username, 问题是这样只能展示,不能进行搜索...哎,好苦恼。
    淡定淡定,不就是多个搜索吗?来,让我告诉你怎么做。

    首先,我们进入 POST 的 model,在一开始的地方添加一个属性:

class Post extends CActiveRecord 
{ 
  public $name; //添加一个 public 属性,代表作者名 
  然后改一下 Model 里面 search 的代码,改动部分都已经加了注释:
public function search() 
{ 
  // @todo Please modify the following code to remove attributes that should not be searched. 
 
  $criteria=new CDbCriteria; 
 
  $criteria->with = array(&#39;author&#39;); //添加了和 author 的渴求式加载 
 
  $criteria->compare(&#39;post_id&#39;,$this->post_id); 
  $criteria->compare(&#39;title&#39;,$this->title,true); 
  $criteria->compare(&#39;content&#39;,$this->content,true); 
  $criteria->compare(&#39;tags&#39;,$this->tags,true); 
  $criteria->compare(&#39;status&#39;,$this->status); 
  $criteria->compare(&#39;create_time&#39;,$this->create_time); 
  $criteria->compare(&#39;update_time&#39;,$this->update_time); 
  $criteria->compare(&#39;author_id&#39;,$this->author_id); 
 
  //这里添加了一个 compare, username 是 User 表的字段,$this->name 是我们添加的属性,true 为模糊搜索 
  $criteria->compare(&#39;username&#39;,$this->name,true); 
 
  return new CActiveDataProvider($this, array( 
    &#39;criteria&#39;=>$criteria, 
  )); 
}


    然后在 view 里面,就是 post 文件夹的 admin.php ,CGridView 改为下面代码:

<?php $this->widget(&#39;zii.widgets.grid.CGridView&#39;, array( 
  &#39;id&#39;=>&#39;post-grid&#39;, 
  &#39;dataProvider&#39;=>$model->search(), 
  &#39;filter&#39;=>$model, 
  &#39;columns&#39;=>array( 
    &#39;post_id&#39;, 
    &#39;title&#39;, 
    &#39;content&#39;, 
    &#39;tags&#39;, 
    &#39;status&#39;, 
    &#39;create_time&#39;, 
    &#39;update_time&#39;, 
    &#39;author_id&#39;, 
    /*下面就是添加的代码啊*/ 
    array( 
      &#39;name&#39;=>&#39;作者名称&#39;, 
      &#39;value&#39;=>&#39;$data->author->username&#39;, //定义展示的 value 值 
      &#39;filter&#39;=>CHtml::activeTextField($model,&#39;name&#39;), //添加搜索 filter 
    ), 
    array( 
      &#39;class&#39;=>&#39;CButtonColumn&#39;, 
    ), 
  ), 
)); ?>

    你是不是发现现在有了搜索框但是不起作用呢?哈哈,所以我们说文章要坚持看到最后。我们要做的最后一步,就是在 rule 里面,把 name 属性加入到安全搜索字段中,要不然会被 Yii 认为是不安全字段而过滤掉的。看,就在下面函数的最后一行,safe 前面多了个 name ....

public function rules() 
{ 
  // NOTE: you should only define rules for those attributes that 
  // will receive user inputs. 
  return array( 
    array(&#39;title, content, status, author_id&#39;, &#39;required&#39;), 
    array(&#39;status, create_time, update_time, author_id&#39;, &#39;numerical&#39;, &#39;integerOnly&#39;=>true), 
    array(&#39;title&#39;, &#39;length&#39;, &#39;max&#39;=>128), 
    array(&#39;tags&#39;, &#39;safe&#39;), 
    // The following rule is used by search(). 
    // @todo Please remove those attributes that should not be searched. 
    array(&#39;post_id, title, content, tags, status, create_time, update_time, author_id, name&#39;, &#39;safe&#39;, &#39;on&#39;=>&#39;search&#39;), 
  ); 
}

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP实现防盗链的方法实例详解

php判断str字符串是否是xml格式数据的方法(详解)

PHP异常处理定义与使用方法详解

以上是PHP中Yii框架的基本用法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn