Introduction to YII Framework

Source: Internet
Author: User
Tags findone

First, installation

PHP Run Environment installation package: http://www.phpstudy.net/a.php/207.html

Yii installation package:

HTTPS://GITHUB.COM/YIISOFT/YII2/RELEASES/DOWNLOAD/2.0.6/YII-BASIC-APP-2.0.6.TGZ (Basic Application template for Yii2)

HTTPS://GITHUB.COM/YIISOFT/YII2/RELEASES/DOWNLOAD/2.0.6/YII-ADVANCED-APP-2.0.6.TGZ (Advanced application template for YII2)

Download the basic Application template for Yii2 and unzip it to the Web site root.

My Site root directory is: F:\testyii

Domain name is: www.testyii.com

Visit http://www.testyii.com/requirements.php to check the installation environment.

Note that the PHP version must be above 5.4.

Configure the cookie Authentication key: File F:\testyii\config\web.php There's a cookievalidationkey in it. Just give me an ABCD character.

Visit http://www.testyii.com/web/index.php See congratulations! Indicates that the installation is complete.

Second, the controller

Controller file Address:F:\testyii\controllers

To create a format:

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Framework Global Class namespace Class TestController extends controller/Controllers name format name Controller hump named file name (testcontroller.php) consistent with class name {    Public Function Actionindex () {//action named Format Action action name        echo ' Hello word ';    }}

Access format: Request Portal? r= Controller name/operation name

Example: Http://www.testyii.com/web/index.php?r=test/index

Note Access to the controller name and operation name here is case insensitive.

Controller parent class source code is F:\testyii\vendor\yiisoft\yii2\web\Controller.php

Control can use the public methods and properties of the parent class, such as using the Jump method Redirect ($url, $statusCode = 302)

Third, receive variables

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Framework Global Class namespace Class TestController extends controller/Controllers name format name Controller hump named file name (testcontroller.php) consistent with class name {    Public Function Actionindex () {//operation named format Action action name        $request = YII:: $app->request;//The request component is obtained through the global class YII $request        $id = $request->get (' id ', ' Default '); Get the data that gets passed through the Get method by requesting the component        echo $id;//If the ID is passed the output ID is not passed, then output default    }}

The source code for the request component is F:\testyii\vendor\yiisoft\yii2\web\Request.php

There are many ways to use the Post method for example to accept post variables

Third, SESSION processing

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Framework Global Class namespace Class TestController extends controller/Controllers name format name Controller hump named file name (testcontroller.php) consistent with class name {    Public Function Actionindex () {//action named Format Action action name        $session = YII:: $app->session;//Get Session component $session        $ Session->open (); Open session        $session [' name '] = ' Zhang San ';//write session        $name = $session [' name '];//Read session        unset ($session [' Name ']); Delete a value in the session        $session->destroy ();//Destroy the session        Echo $name;    }}

In the above code, I get the $session component through the Yii global class, which is an object, but then I manipulate it as an array. This is because the session component implements PHP's built-in Arrayaccess interface.

The source of the Session component is:F:\testyii\vendor\yiisoft\yii2\web\Session.php

Iv. COOKIE Processing

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Namespace of the framework global class use Yii\web\cookie;class TestController extends controller//director named Format name Controllers Hump nomenclature File name (testcontroller.php) consistent with class name {public    function Actionindex () {//action named Format Action action name        //Get Response Component Cookie Object        $ cookies = YII:: $app->response->cookies;         Cookie data waiting to be written        $cookie _1 = Array (' name ' = ' age ', ' value ' =>18);         $cookie _2 = Array (' name ' = ' gender ', ' value ' = ' male ');        The Add method accepts a cookie class-generated object        $cookies->add (New cookie ($cookie _1));//write Cookie        $cookies->add (New cookie ($ cookie_2));         echo $cookies [' age ']; Read Cookie        unset ($cookies [' age ']);//delete cookie    }}

Note that the code here also takes a namespace.

The source code for the Cookie class is:F:\testyii\vendor\yiisoft\yii2\web\Cookie.php

As can be seen from the source, the array waiting to be written to the cookie, in addition to the name value can also have domain expire path secure httponly and other data

The generation of the cookie object within the response component source:F:\testyii\vendor\yiisoft\yii2\web\CookieCollection.php

It is also useful to see from the source that it has a getValue ($name, $defaultValue = null) method.

Five, the data model

Prepare two tables:

CREATE TABLE ' user ' (  ' uid ' int (one) not NULL auto_increment COMMENT ' userid ',  ' uname ' varchar ') NOT NULL DEFAULT ' ' COMMENT ' username ',  ' upass ' varchar (not NULL DEFAULT ' COMMENT ' password ',  PRIMARY KEY (' uid ')) Engine=myisam Auto_inc rement=2 DEFAULT charset=utf8 comment= ' user table ';  CREATE TABLE ' log ' (  ' log_id ' int (one) unsigned not null auto_increment,  ' uid ' int (one-by-one) not null DEFAULT ' 0 ' COMMENT ' operator ID ',  ' content ' varchar (8000) NOT null default ' COMMENT ' Operation Contents ',  ' create_time ' int (one-by-one) NOT null default ' 0 ' C Omment ' Create Time ',  PRIMARY KEY (' log_id ')) Engine=myisam auto_increment=2 DEFAULT Charset=utf8 comment= ' User action Log table ';

To configure YII connection database information: F:\testyii\config\db.php

<?phpreturn [    ' class ' = ' yii\db\connection ',    ' dsn ' = ' mysql:host=localhost;dbname=test ',//Specify Database    ' username ' + ' root ',    ' password ' = ' root ',    ' charset ' and ' UTF8 ',];

Model file Address:F:\testyii\models

To create a model:

There is a user.php in the folder F:\testyii\models with the name of the User table I just created, I'll make a backup of it, and then create a new user.php

The name of the model is consistent with the class name and the table name.

<?phpnamespace App\models; The model must be placed in this namespace with the use Yii\db\activerecord; Namespace for model-inherited classes class User extends ActiveRecord {}

ActiveRecord class Source Address:F:\testyii\vendor\yiisoft\yii2\db

Insert data using the Model:

Before inserting a form I first create a validation rule in the model, more information about the authenticator http://www.yiichina.com/doc/guide/2.0/tutorial-core-validators

<?phpnamespace App\models; The model must be placed in this namespace with the use Yii\db\activerecord; Namespace for model-inherited classes class User extends ActiveRecord {public    function rules () {        return [[            ' uname ', ' UPass '], ' trim '],//Remove Space            [[' uname ', ' UPass '], ' required '],//must be filled in            [' uname ', ' string ', ' min ' =>5, ' Max ' =>20],//Limit character length c6/>[' UPass ', ' string ', ' min ' =>6, ' Max ' =>50], '        ;    }}

Then go back to the controller and insert the data using the user model

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Namespace of the framework global class use App\models\user;class TestController extends controller//director named Format name Controllers Hump nomenclature The file name (testcontroller.php) is consistent with the class name {public    function Actionindex () {//operation named format Action action name        $user = new user;//instantiate Model object 
    $user->uname = ' Zhangsan '; Data to be inserted        $user->upass= ' 888888 ';        The validation data successfully returns TRUE if the failure returns false        if (! $user->validate ()) Die (' Error ');        $uid = $user->save (); Insert data        $uid = $user->attributes[' uid '];//get self-increment ID        echo $uid;    }

Find data using the model:

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Namespace of the framework global class use App\models\user;class TestController extends controller//director named Format name Controllers Hump nomenclature The file name (testcontroller.php) is consistent with the class name {public    function Actionindex () {//operation named format Action action name        $user = new user;//instantiate Model object 
   //1. Executes a query statement        $sql = "SELECT * from user";        $results = $user->findbysql ($sql)->all (); The all method returns a two-dimensional array one  method that returns a one-dimensional array        $one _user = $results [0]->attributes ();//gets all the data for a record        $one _user_name = $ results[0]->uname; Get a value for a record        //print_r ($one _user);        Print_r ($one _user_name);                2. Query a record        $results = User::find ()->where ([' uid ' = 1])->one ()->toarray ();//returns the array format        directly Print_r ($results);    }}

For more information about the query Http://www.yiichina.com/doc/api/2.0/yii-db-activerecord

Modify data using the model:

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Namespace of the framework global class use App\models\user;class TestController extends controller//director named Format name Controllers Hump nomenclature The file name (testcontroller.php) is consistent with the class name {public    function Actionindex () {//operation named format Action action name        $user _obj = user::findone (1) ; The object that gets the data with the primary key UID 1        $user _obj->upass = 111111;//Modify the password        if ($user _obj->update ()!== false) {            echo ' Update successful ';        } else {            echo ' update failed ';}}    }

Delete data using the model:

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Namespace of the framework global class use App\models\user;class TestController extends controller//director named Format name Controllers Hump nomenclature The file name (testcontroller.php) is consistent with the class name {public    function Actionindex () {//operation named format Action action name        $user _obj = user::findone (1) ; The object that gets the data for the primary key UID is 1        if ($user _obj->delete ()!== false) {            echo ' delete successful ';        } else {            echo ' Delete failed ';}}    }

Associated queries using the model:

The following shows the association operation for the user table associated with the user log table.

Insert two records into log table

Insert INTO ' log ' values (' 1 ', ' 2 ', ' hehe ', ' ten '); insert into ' Log ' values (' 2 ', ' 2 ', ' haha ', ' 20 ');

Create a log model F:\testyii\models\Log.php again.

<?phpnamespace App\models; The model must be placed in this namespace with the use Yii\db\activerecord; Namespace for model-inherited classes class Log extends ActiveRecord {    }

And back to the controller.

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Namespace of the framework global class use App\models\user;use App\models\log;class TestController extends controller//director named format name controllers Hump method named file name (testcontroller.php) consistent with class name {public    function Actionindex () {//action named Format Action action name//one        -to-many relationship query        $user _ obj = User::findone (2);        $logs = $user _obj->hasmany (' App\models\log ', [' uid ' = ' uid '])->asarray ()->all (); The first UID is the second UID of the log table, which is the        //print_r ($logs) of the user table;        One-to-one relationship query        $log _obj = log::findone (1);        $user = $log _obj->hasone (user::classname (), [' uid ' = ' uid '])->asarray ()->one (); This code is best placed inside the LOG model        Print_r ($user);}    }

Vi. views

View file Address: F:\testyii\views\ controller name \ View name. php

CREATE VIEW: F:\testyii\views\test\index.php

<?= $name? ><?= $age?>
<?=print_r ($age)?>

Call View:

<?phpnamespace app\controllers; Controller namespace use Yii\web\controller; controllers inherit the controller class's namespace use \yii; Framework Global Class namespace Class TestController extends controller/Controllers name format name Controller hump named file name (testcontroller.php) consistent with class name {    Public Function Actionindex () {//operation named format Action action name        $result = Array (' name ' = ' Zhang San ', ' age ' =>18, ' arr ' =>array (' A ', ' B '));        return $this->renderpartial (' index ', $result); Call the view and inject the variable into the View    }}

Safe output data in view:

<?php use    yii\helpers\html;//escape use    yii\helpers\htmlpurifier;//filter? ><?=html::encode ($name)?> <?=htmlpurifier::p rocess ($name)?>

More information about views Http://www.yiichina.com/doc/guide/2.0/structure-views

Introduction to YII Framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.