search
HomeBackend DevelopmentPHP TutorialBasic usage of Yii framework in PHP

Basic usage of Yii framework in PHP

Jun 07, 2018 pm 02:34 PM
phpyii

This article mainly introduces the basic usage of Yii framework in PHP. Interested friends can refer to it. I hope it will be helpful to everyone.

In the code automatically generated by Yii, we can always see CGridView in the admin interface. This is a very useful table control for displaying data. If used well, it can significantly speed up the development progress. Let's explore the basic use of 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='日志表';

Two tables, one storing author information and the other storing logs, where the logs have a foreign key associated with the user. The is_delete field in the two tables marks whether the record has been deleted, 0 means not deleted, and 1 means deleted. Let's take a look at the relation method of the Post class generated with gii:

/** 
 * @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'), 
  ); 
}

The author foreign key exists as a BELONGS_TO relationship, which is in line with our expectations.
Having said so much, let’s take a look at the code of CGridView in admin.php in the automatically generated Post:

<?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;, 
    ), 
  ), 
)); ?>

Look! Although we haven't written anything, this is the most basic use of this control. dataProvider is the data provided by the search function in the model. Filter... I can’t see the role here for the time being. Columns control each column displayed. The last item of CButtonColumn shows us three buttons, namely View Update and delete.
Next we will transform it bit by bit.

Use CGridView to display the data form we really want: Many times, the things in the database are not suitable to be displayed directly to the user. We need It is suitable for reading only after certain processing. But without modification here, CGridView will only present the database value unchanged, so we should modify it in the corresponding field. For example, in the is_delete field, 0 and 1 are stored in the database, but it is not very good to read here. We should change it to 1 to display 'yes' and 0 to display 'no'. Take a look at the code below. We use an array. The two keys are name and value. Name corresponds to the fields owned by the model, and value is the data you want to display. It can be written as a php statement as code executed. Seeing this, do you think we can do a lot with this value? Some students may ask, if the code I want to execute is very long, is it all written in value? . . . I said classmate, wouldn’t you write a function somewhere else and then call it here? ?

<?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;, 
    ), 
  ), 
)); ?>

In addition, there are some commonly used options, which can be filled in the array. The following is the more common usage (other parts of the code are omitted):

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 的类 
),

Above we use As for name, it is an original field in the model. If we want to display the new content defined by ourselves, use header:

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

to add CCheckBoxColumn: Sometimes we may need a check box box to select each row. At this time, we can add a column and use the CCheckBoxColumn class:

<?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;, 
    ), 
  ), 
));

to modify the ButtonColumn: Did you notice the last three small icons of each item in the list? ? Of course, if you don’t need them, just delete them directly. But what if you only want a few of them? You can add a template parameter:

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

You can also customize the button:

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"), 
        ), 
      ), 
    ),

Trigger Javascript when refreshing: If you want to trigger some Javascript after each search, Yii This option is also provided. You just need to write it as a function and set afterAjaxUpdate. Remember that this is only called after the ajax request is completed. If you want to call it as soon as the page is loaded, you need to add additional Javascript## to the page. #

  $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;), 
    ), 
    ....

Add search for related fields of related tables: Let me start by saying that we only talk about "one-to-many" related searches here. First of all, don't forget our database. If you forget, please ask Click here: Here, you can see that there is a foreign key in tbl_post associated with the tbl_user table to find author-related information. After building the database, take a look at the POST Model of the Yii code we generated. The realtion inside is as follows (ignore the 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;), 
  ); 
}

You can see that the POST and USER tables can be accessed through the author key, for example: $model->author->nickname, and here is the BELONGS_TO relationship.

Having said so much, what exactly are our needs? ....

The product manager pushed up his glasses: "We want to add a function to the backend management interface of the log, which allows you to search for corresponding articles by author name. This is urgent and will be completed tonight." "

    淡定淡定,不就是改需求吗。忽略进度要求,我们研究一下究竟要做什么。
    其实很简单的,不就是在 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异常处理定义与使用方法详解

The above is the detailed content of Basic usage of Yii framework in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.