Yii2 Advanced

filter

what is a filter

A filter is code that needs to be executed before or after a controller action is executed. The code is executed in the form of an object, it should be defined and declared in the form of a class.
A filter is essentially a special behavior.

Why use filters

Usually, the filter binds the code to all operations, that is, the execution of each operation requires the filter to be executed first or later, so it can be used to perform permission detection, cache processing, etc.

where to use the filter

In the controller, define:
public function behaviors(){
}

Filter details

The ==behaviors() method returns an array, similar to the configuration file==
each element in the array should also be an array, representing a filter
such as:

Public function behaviors(){
Return [
[
'class' => 'implementation class',
]
];
}
indicates that a filter is defined

filter location

Yii2 defines a lot of filters for developers, which can be used directly.

filter position.png

define filter

In Yii2, to customize filters, you need to inherit the yii\base\ActionFilter class and override the yii\base\ActionFilter::beforeAction() and/or yii\base\ActionFilter::afterAction() methods to create the action filter
definition The code in beforeAction() will be executed before the action is executed The code
defined in afterAction() will be executed after the action is executed

For example: to create a filter to record the execution time of the operation,
you should first create a filter, for example, create a filters directory in the frontend application, which is specially used to store the filter, and then create the TimeFilter.php file The filter usually uses Filter.php as the file suffix, and there should be a class in the file with the same name as the file

filter position 1.png

filter.png

 

Then override the beforeAction and afterAction of the base filter

filter application.png

 

In beforeAction, if it returns true, it means release, and the operation continues, if it returns false, it means stop, and the operation is no longer executed.

load filter

filter loading.png

Points to pay attention to:
==Define the beforeAction and afterAction in the filter, and must return the method of the parent class.
Return parent::beforeAction($action)==

error handling

  1. All non-fatal errors are thrown as exceptions, which can be caught
  2. Error handlers are configured in main in the form of components
  3. The format of the error response is optional, ajax or html or plain text
  4. The method of responding to the error can be defined by yourself.
    The essential class of the error component is yii\web\ErrorHandle. Other configuration parameters can go to this class to view the public properties

Use of Session

Session use.png

Use of Cookies

//获取cookie的对象
$getCookieObj = Yii::$app->request->cookies;

//设置cookie的对象
$setCookieObj = Yii::$app->response->cookies;

/**
 * 添加cookie
 * 注意:
 * 使用add来添加add的参数必须是yii\web\Cookie对象
 */
$setCookieObj->add(new Cookie([
    'name' => 'tel',
    'value' => '15730436354',
    'expire' => time()+20
]));

/**
 * 获取值时有三种方法
 */
//获取的是cookie的值
var_dump($getCookieObj->getValue('tel', '00000'));
//获取的是对象
var_dump($getCookieObj->get('tel'));
//获取的是对象
var_dump($getCookieObj['tel']);

File Upload

Uploading files in Yii usually uses the yii\web\UploadedFile class, which encapsulates each uploaded file into an UploadedFile object. Combined with yii\widgets\ActiveForm and models, you can easily implement a secure file upload mechanism

Create a model

Like a normal text input box, create an attribute in models to represent a field, and then perfect the validation rules.

Create model.png

Create controllers, instantiate form models and render views

create controller.png

Use ActiveForm to create form elements in views

Create element form.png

Receive form data in controller and bind data to form model

form model.png

Note: To call the upload function, you need to open the php_fileinfo extension
uploads directory should be in the same level directory of the entry file

Multiple file upload

Yii2 supports multiple file uploads, just add some small modifications to the above example

Modify the form model

Adding the maxFiles configuration to the verification indicates how many files can be uploaded at most

Modify the upload method of the form model

If it is a multi-file upload, $this->imageFile here will be an array, so you can use foreach to save the file

View file modification

If you need to pass in multiple files, you need to add [] to the form name attribute plus the multiple attribute

 

Controller modification

The controller receives multiple files and should use the getInstances method in UploadedFile to bind properties

 

verification code

Captcha in Yii2 is implemented through an extended action, called
yii\captcha\CaptchaAction
, which can be accessed directly by binding it to actions without any changes:

 

Configurable captcha properties

Since CAPTCHA is a public operation, we can easily find its implementation class. Various properties in the implementation class can be considered as configurable properties
such as:

public $width=120;

You can also set:
height: height
backColor: background color
foreColor text color
minLength minimum length (number of characters)
maxLength maximum length
fontFile font file
.....

Use captcha in view

 


Use the widget() method to call the verification code module, and specify the displayed DOM structure
{image} to display the verification code image
{input} to display the verification code input box

 

Verify verification code

After the verification code is filled in, you need to use the verification mechanism to complete the verification of the verification code. In Yii2, you don't need to write the verification yourself, you can directly call the captcha verification in the rules of the form model.

['verifyCode','captcha'],

Data paging

Yii2 also provides a data paging class similar to TP:
\yii\data\Pagination
To use it, you need to instantiate it first:
when instantiating, you need to pass in the total number of data and the number of pieces displayed on each page

Operation in the controller

public function actionList()
    {
        //获取页码,参数需和Pagination中配置的参数一致
        $page=Yii::$app->request->get("page");
        $page=($page-1)>0?($page-1):0;
        $pageSize=5;
        //设置分页配置
        $config=[
            'totalCount' => User::find()->count(),
            'defaultPageSize' => $pageSize,
            'pageParam' => 'page',
        ];
        //实例化分页器,将配置参数传入到Pagination中
        $paginationObj = new Pagination($config);
        $rows =User::find()->asArray()->offset($page*$pageSize)->limit($pageSize)->all();
        return $this->render('list',[
            'rows'=>$rows,
            'pagebar' => $paginationObj
        ]);
    }

Action in view

To display paging in the view, use the LinkPager widget
How to use:

<?=\yii\widgets\LinkPager::widget([
        'pagination' => $pagebar
]) ?>

You need to pass in a pagination object, which is $pages;



Author: meteorites
Link: https://www.jianshu.com/p/556fb244e96d
Source: Jianshu
The copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

 
 
G
M
T
 
 
Detect languageAfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu
 
AfrikaansAlbanianArabicArmenianAzerbaijaniBasqueBelarusianBengaliBosnianBulgarianCatalanCebuanoChichewaChinese (Simplified)Chinese (Traditional)CroatianCzechDanishDutchEnglishEsperantoEstonianFilipinoFinnishFrenchGalicianGeorgianGermanGreekGujaratiHaitian CreoleHausaHebrewHindiHmongHungarianIcelandicIgboIndonesianIrishItalianJapaneseJavaneseKannadaKazakhKhmerKoreanLaoLatinLatvianLithuanianMacedonianMalagasyMalayMalayalamMalteseMaoriMarathiMongolianMyanmar (Burmese)NepaliNorwegianPersianPolishPortuguesePunjabiRomanianRussianSerbianSesothoSinhalaSlovakSlovenianSomaliSpanishSundaneseSwahiliSwedishTajikTamilTeluguThaiTurkishUkrainianUrduUzbekVietnameseWelshYiddishYorubaZulu
 
 
 
 
 
 
 
 
 
Text-to-speech function is limited to 200 characters
 
 
Options : History : Feedback : Donate Close

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325255984&siteId=291194637
Recommended