Basic Summary 1. Modify the default controller/method
Yii default is the site controller, you can set the $config in the web.php ' defaultroute ' = ' xxxx '; Use a custom default controller. You can also rewrite the Yii:: $app->defaultroute property.
The default method for Yii is index, which can be initially set in vender/yiisoft/yii2/base/controller.php, or defaltaction= ' action ' can be overridden in the controller.
2. Add a standalone module
Yii can add a custom module to the Modules folder and add the ' modules ' =[id= in the $config in web.php after completion. Class= ...] Sets the switch for the module.
Modules are generally used for some independent functions, like the admin module in my station overall responsible for the background logic.
3. Model Action table settings
Yii models have model and ActiveRecord two kinds, the model class is used to deal with basic business logic, there is no database-related method, if you want to manipulate the same name data table, inherit the ActiveRecord class.
We use a operation.class operation class in the Models folder to inherit the Yii\db\activerecord to manipulate the operation table.
You can also override the public $tableName property to set if you want to manipulate other tables. or overwrite its TableName method (note is static method): public static function TableName () {return ' TableName '}
4. View Layer Composition
Yii's view layer uses. php files, and its internal implementations are also used in the form of Yii's built-in widgets, such as <?= linkpager::widget ([' pagination ' + $pagination])?> to represent their paging class.
Also, widgets like input, shown with the ActiveForm class, Yii will automatically add AJAX validation to each, and its general widgets are placed in yii\widget\, and we can also build custom widget classes in this folder.
5. Layout mode
Yii will turn on layout mode by default and its layout template is main.php in view, we can public $ in veder/yiisoft/yii2/web/controller.php base class The Layout property modifies the configuration of the template file.
We can also set off or specify a specific layout:
- Control public $layout =false/' layout ' in controller
- Controller member method Internal control $this->layout=false/' layout '
- Select Layout $this->context->layout=false/' layout ' in the view
6. Basic setup of the model
The YII model is the MVC processor, which performs the processing of MVC logic. The property definition of model is its core, because the Magic method Get/set is defined by default, so you can get/assign the properties of the model directly by using $modle->attr= ' value ' in the models.
Scene settings
There is a definition of the scene in Yii, which allows Yii to return different data information in different situations. Use the model's scenarios () method to set the return data.
When we use model, we pass in the scene name $model =new model ([' Scenario ' = ' login ']) to determine the scene.
Rule settings
The definition of validation rules in Yii, using the Rules () method, allows you to define multiple rules in one line or define them according to different scenarios. External validation uses the $model->validate () method to perform validation.
In safe mode, to secure authentication, that is, each attribute is validated in rules, and if there is no specific rule, add ' safe ' validation. Otherwise, the validation fails and the database is saved.
Label settings
When working with a form, use the $model->attributes property to represent all properties. Where the Attributelabels method return an array to represent the label label of each individual form item produced by ActiveForm in the view layer
7. Referencing the Js/css file
The view in Yii also uses the object-oriented approach, so the introduction of CSS and JS files to use a special method.
- Use $this->registerjsfile (' js.js ') to introduce JS files;
- Use $this->registerjsfile (' js.js ') to introduce JS files;
8. Use of the paging class
The total quantity calculated in the model $count= $this->find ()->where ()->count ();//Use the total number of bars and set the number of pages per page to instantiate a Yii\data\pagination class $page=new Pagination ([totalcount ' = $count, ' defaultpagesize ' + 2,]);//Use the properties of the paging class to search for the desired data and return the data $res= $this->find ( )->where ()->offset ($page->offset)->limit ($page->limit)->all (); return [$res, $page];//render the page using the controller $data = $model->getdata (); return $this->render (' index ', $data);//Use the data in the View page. foreach ($res as key) ... yii\widgets\linkpager::widget ([pagination= $page, prevpagelabel= ' prev ']).
9. Create a URL
Use Yii\helpers\url; Url::to ([' xxx/xxx ']);//or Yii:: $app->urlmanager->createurl (' xxx.xxx ')
10 Query Builder
Yii Query Statement constructor is very simple and useful, it can be used in the model and controller, although it may cause the model and the table does not correspond, but its composition is close to the SQL statement, using it can easily write complex SQL statements without strict adherence to Yii's built-in rules.
The method is:
$res = (new Yii\db\query ())->select ()->from ()->leftjoin ()->where-> ()->all ();
Where statements are more complex:
Where (' in ', ' id ', $array) or where (' id ' = = $array)
You can see the resolution of the Where method in Http://www.yiichina.com/doc/guide/2.0/db-query-builder.
11. Custom Functions
Yii inside the custom function can be in the vendor/yiisoft/yii2/helpers/folder, create a new xxx.php file, then define a custom class, and then define the static method Yyy ().
Apply the base namespace when used, use yii\helpers\xxx, and then use the class to refer to the base static method Xxx::yyy ()
12. Correlation model
An association model within Yii that takes a record of the corresponding table when a record in the current table is taken. If every piece of information is taken out in table A, also take out B table and a table to the due information, define a getbtable method in Modela
function getbtable () { return $this->hasone/hasmany (btable::classname,[' bid ' = ' aid ');}
You can use a query to joinWith(‘Btable‘)->find();
find its associated object when you find it, or you can use method result objects such as $this->find ()
Use $res->btable to refer directly to an object.
Use $res[n]->btable->attr to refer to the corresponding properties of Table B.
13. Create a form using ActiveForm
To create a view view using widgets in YII2: Set a model to set its properties
Public $username;p ublic $password;
Set its rule or scene, etc.
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 in the page
Use yii\widgets\activeform;<?php $form = Activeform::begin ([' action '] = [' Log/login '], ' method ' = ' Post ' ]);?> <?= $form->field ($model, ' username ')?> <?= $form->field ($model, ' Password ')?> <div class= "Form-group" > <?= Html::submitbutton (' Submit ', [' class ' = ' btn ') Btn-primary '])?> </div><?php activeform::end ();?>
14. Using the Verification code
An independent method of setting the verification code in the controller
Public function Actions () { return [ ' captcha ' + = ' class ' = ' yii\captcha\captchaaction ', ' height ' = +, ' width ' = +, ' minLength ' = 4, ' maxLength ' = 4 ], ]; }
Set rule in model and Label,label ibid.
Public Function Rules () { return [[' Verifycode ', ' captcha ', ' captchaaction ' = ' Admin/log/captcha '],];}
(Captchaaction to be set to the position in the controller, if the custom module is to set module) in view
Use yii\captcha\captcha;<?= $form->field ($model, ' Verifycode ')->widget (Captcha::classname (), [' Captchaaction ' + ' Log/captcha ', ' imageoptions ' and ' = ' alt ' = ' Click to change ', ' style ' = ' cursor:pointer ' ] ])?>
15. Use of blocks in views
Block content is defined between $this->beginblock ([' ID ' =>xxx]) and $this->endblock (), and is referenced in layout using $view->block[id]. You can import view data into the template when you are finished.
You can also define $this->var=xxx; to be referenced in layout with $this->var.
16. Update and delete updates
Find a result $res= $this->find ()->where ()->one ();//Modify the result to $res->attr= ' xxx ';//Perform update operation $res->update ();
Delete
Delete a data $this->findone ($id)->delete ();//delete all eligible data $this->deleteall ([where]);
Attention and tips 1. Jump between URL modules
When you create a URL in a module with the Url::to () method, the module name is automatically added before, which prevents you from jumping to another module, and we can add '//' characters before the string to return to the root module, such as url::to (['//index/index ']) to jump to the initial address.
2. Initializing variables
To initialize a variable before each operation in the controller, do not rewrite the __construct constructor, because it needs to pass in various variables. It is best to rewrite the beforeaction () function, which executes every action.
Also note: At the end of the method, be sure to add the return true statement.
3. Using Yii variables in JS
If you want to use the URL variable of yii in JS, you can use the script tag in HTML to parse the variable in the first render view and put the following code before you need to use the variable.
<script type= "Text/javascript" > var key= "<?=url::to ([' xxx/xxx '])?>" </script>
Then in the JS file normal use.
4. Definition of global constants
We can define global constants in params.php in the Config folder.
It is then referenced in the script using Yii:: $app->params[' key ').
5.yii model property to array
Yii uses the ToArray () method to convert the properties of a model to an array for output, to be used independently, or to be used in continuous operation at query time.
6. When rendering a view page using a controller, be sure to add echo or return to the Echo/return $this->render (' View ', $data) in front of Render, and remember the properties in 7.yii! In ActiveForm If you have this field in your datasheet, you should not declare a property with public, which will cause attribute to be unable to assign a value .... (Tears of Blood).
YII2 Development PostScript