Yii2 development postscript

Source: Internet
Author: User
After yii2 development, I wrote my blog CMS a few days ago. when considering the PHP framework, I thought of yii, which is said to be very powerful. when I got started with yii, I found Version 2.0, which was the best choice. This attempt seems to be a pitfall. yii2.0 was released in December 2014. it is estimated that there are fewer people in China and less information. Baidu yii2.0 found many answers to version 1.0 in case of problems, I had to go to google to check the English site. No one reminded me of a small problem, and stack overflow turned the source code by itself. it took more than a day... It can be said that it has suffered a lot.

But the website is finally made, address: http://www.alwayscoding.cn, after the blog on this site synchronously updated, and, I can also in the above unscrupulous put their favorite articles ~~ In addition, the source code is also on github at: https://github.com/zhenbianshu/blog-cms. if you want to use this cms, you can continue to support it ~ Finally, I have summarized the following usage experiences. if you are ready to start yii2.0, you can take a look and leave a claw.

Summary 1. modify the default controller/method

Yii is the site controller by default. you can set 'defaultrotu' = 'xxxx' in $ config in web. php and use the custom default controller. You can also rewrite the Yii: $ app-> defaultRoute attribute.

The default method of yii is index. you can perform initial settings in vender/yiisoft/yii2/base/Controller. php, or rewrite defaltAction = 'action' in the Controller '.

2. add independent modules

Yii can add a custom module in the modules folder. in $ config of php, 'modules' = [id = .. class =...] set the switch of the module.

The module is generally used for some independent functions. for example, the admin module in my website is responsible for the background logic as a whole.

3. model operation table settings

There are two types of yii models: Model and ActiveRecord. The Model class is used to process basic business logic without database-related methods. to operate a data table with the same name, inherit the ActiveRecord class.

We use an Operation class in Operation. class in the models folder to inherit yii \ db \ ActiveRecord to operate the Operation table.

If you want to operate on other tables, you can also rewrite the public $ tableName attribute. Or rewrite the tableName method (note the static method): public static function tableName () {return 'tablename '}

4. View layer structure

The view layer of yii uses the. php file, and its internal implementation mostly adopts the form of yii built-in widgets, such $ Pagination])?> To indicate its paging class.

In addition, components such as input are displayed using the ActiveForm class. yii will automatically add ajax verification to each component, and its general widgets are placed in yii \ widget, we can also build custom widget classes in this folder.

5. layout mode

Yii will enable the layout mode by default, and its layout template is main. php, we can go to veder/yiisoft/yii2/web/controller. modify the configuration of the template file using the public $ layout attribute in the php basic class.

We can also disable or specify a specific layout:

  • Public $ layout = false/'layout 'in the controller'
  • Controller member Method control $ this-> layout = false/'layout'
  • Select layout $ this-> context-> layout = false/'layout 'in the view'
6. Basic model settings

The yii model is the MVC processor that processes the MVC logic. The attribute definition of the model is its core. because the magic method get/set is defined by default, you can directly call $ modle-> attr = 'value' outside the model ', obtain/assign values to model attributes.

Scenario settings

Yii has a definition of a scenario. defining a scenario allows yii to return different data information under different circumstances. Use the scenarios () method of the model to set the returned data.

When using the model, we input the scenario name $ model = new Model (['scenario '=> 'login']) to determine the scenario.

Rule settings

In yii, the validation rules are defined. you can use the rules () method to define multiple rules one by one or according to different scenarios. For external verification, use the $ model-> validate () method for verification.

In security mode, security verification is required, that is, each attribute must be verified in rules. If no specific rule exists, 'Safe 'verification must be added. Otherwise, the verification fails and the database fails to be saved.

Tag settings

When processing a form, $ model-> attributes are used to indicate all attributes. The attributeLabels method returns an array to indicate the label labels of each form item generated by ActiveForm in the view layer.

7. Reference JS/CSS files

View in yii also uses the object-oriented method, so special methods are used to introduce CSS and JS files.

  • Use $ this-> registerJsFile ('JS. js') to introduce js files;
  • Use $ this-> registerJsFile ('JS. js') to introduce js files;
8. Use of paging classes
// Calculate the total number in the model $ count = $ this-> find ()-> where ()-> count (); // instantiate a yii \ data \ Pagination class $ page = new Pagination ([totalCount '=> $ count, 'defaultpagesize' => 2,]); // use the pagination class attribute to search for the expected data and return the data $ res = $ this-> find ()-> where () -> offset ($ page-> offset)-> limit ($ page-> limit)-> all (); return [$ res, $ page]; // use the controller to render the page $ data = $ model-> getData (); return $ this-> render ('index', $ data ); // use data on The View page. Foreach ($ res as key)... yii \ widgets \ LinkPager: widget ([pagination = $ page, prevPageLabel = 'previous page']).
9. create a url
Use yii \ helpers \ Url; Url: to (['XXX/xxx']); // or Yii: $ app-> urlManager-> createUrl ('XXX. xxx ')
10 Query Builder

The QUERY statement constructor in yii is very simple and easy to use. it can be used in models and controllers. Although the model may not correspond to the table, it forms a similar SQL statement, using it, you can easily write complex SQL statements without strictly following the yii built-in rules.

Method:

$res=(new yii\db\Query())->select()->from()->leftJoin()->where->()->all();

Where statements are complex:

Where ('in', 'id', $ array) or where ('id' => $ array)

For more information, see the whereworkflow in http://www.yiichina.com/doc/guide/2.0/db-query-builder.

11. user-defined functions

In yii, you can create a XXX. php file in the vendor/yiisoft/yii2/helpers/folder, define a custom class, and then define the static method YYY ().

When using the base namespace, use yii \ helpers \ XXX, and then use the class to reference the base static method XXX: YYY ()

12. associate model

The association model in yii is used to retrieve the records of the corresponding table when a record in the current table is obtained. For example, if every piece of information in Table A is taken out, the corresponding information in Table B is also taken out to table A, and A getBtable method is defined in ModelA.

function getBtable(){    return $this->hasOne/hasMany(Btable::className,['bid'=>'aid']);}

During query, you can use joinWith ('btable')-> find (); the associated objects will be searched; you can also use methods such as $ this-> find () to result objects.

Use $ res-> btable to directly reference objects.

Use $ res [n]-> btable-> attr to reference the corresponding attributes of Table B.

13. use ActiveForm to create a form

To create a view using a widget in yii2: set a Model to set its properties

public $username;public $password;

Set its rule or scenario

public function rules(){    return [            [['username', 'password','conpass'], 'required'],            ['conpass', 'password',        ];}

Set its label

Public function attributeLabels () {return ['username' => 'admin', 'password' => 'password',];}

Then, render the model instance in the controller:

$this->render('index',['model'=>(new Model/ActiveRecord)])

Finally, use ActiveForm on the page.

use yii\widgets\ActiveForm;
  ['log/login'],    'method'=>'post'    ]); ?>    
 field($model, 'username') ?>    
 field($model, 'password') ?>    

'btn btn-primary']) ?>

14. use the verification code

Independent method for setting verification codes in controller

public function actions() {        return [            'captcha' =>  [                'class' => 'yii\captcha\CaptchaAction',                'height' => 50,                'width' => 80,                'minLength' => 4,                'maxLength' => 4            ],        ];    }

Set rule and label in model. the label is the same as above.

public function rules(){    return [['verifyCode', 'captcha','captchaAction'=>'admin/log/captcha'],];}

(CaptchaAction must be set to the position in the controller. if the custom module needs to be set to the module, use

Use yii \ captcha \ Captcha;
 Field ($ model, 'verifycode')-> widget (Captcha: className (), ['captchaaction' => 'Log/captcha ', 'imageoptions' => ['alt' => 'Click to change the image', 'Style' => 'cursor: pointer '])?>
15. use of blocks in a view

The block content is defined between $ this-> beginBlock (['id' => xxx]) and $ this-> endBlock, use $ view-> block [id] in layout to reference it. You can import view data to the template.

You can also define $ this-> var = xxx; in layout, use $ this-> var to reference it.

16. update and delete

Update

// Find a result $ res = $ this-> find ()-> where ()-> one (); // modify the result $ res-> attr = 'XXX'; // execute the update operation $ res-> update ();

Delete

// Delete a piece of data $ this-> findOne ($ id)-> delete (); // delete all qualified data $ this-> deleteAll ([where]);
Note and tip 1. jump between URL modules

When the Url: to () method is used to create a URL in the module, the module name is automatically added to the front, so that the module cannot be redirected to other modules, you can add the '//' character before the string to return the root module. for example, Url: to (['// index/index']) indicates that the Url is redirected to the initial address.

2. initialize the variable

Do not override the _ construct constructor to initialize a variable before each operation in the controller, because it needs to input various variables. It is best to rewrite the beforeAction () function, which will execute every action.

Note: The return true statement must be added at the end of the method.

3. use the YII variable in JS

If you want to use yii url variables in JS, you can use the script tag in html to parse the variables in advance when rendering the view for the first time, place the following code before the variable is needed.

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.