7 commonly used YII skills knowledge

Source: Internet
Author: User
Tags log log yii

In learning YII and the use of the process, summed up a number of skills and knowledge points, to facilitate their own memory. Here to share with you.

1, not through the log to get AR execution of native SQL statements and print variable data

$query = User::find ()->select ([' username ')->where ([' ID ' =>[1,2,3,4])//Get the AR raw SQL in YII2

$commandQuery = Clone $query; echo $commandQuery->createcommand ()->getrawsql (); $users = $query->all ();

The print variable data can be written like this://reference namespace use yii\helpers\vardumper;//

Vardumper::d UMP ($VAR);//use 2 The second parameter is the depth of the array the third parameter is whether to show code highlighting (not shown by default)

Vardumper::d UMP ($var, Max, true);

2. Returns a one-dimensional array from a two-dimensional database and implements categorical data filtering in conjunction with the Rules validation rule.

A two-dimensional array of normal return table records

Member::find ()->select (' userid ')->asarray ()->all ();

Array

(

[0] = = Array

(

[UserID] = 1

)

[1] = = Array

(

[UserID] = 2

)

[2] = = Array

(

[UserID] = 3

)

)

Returns a one-dimensional array of fields

Member::find ()->select (' userid ')->asarray ()->column ();

Or:

\yii\helpers\arrayhelper::getcolumn (Member::find ()->all (), ' userid ')

Array

(

[0] = 1

[1] = 2

[2] = 3

)

Returns a one-dimensional array with validation rules to verify the correctness of the data, such as classification catid correctly divided into only 1-4, but in devtools open modify CATID to 5, the submission will also go to the database, at this time the rules validation rule is as follows:

[' catid ', ' in ', ' range ' = Category::find ()->select (' id ')->asarray ()->column ()],

Of course, this can also be written in the following way, the same:

[' catid ', ' in ', ' range ' = \yii\helpers\arrayhelper::getcolumn (Category::find ()->all (), ' catid ')],

This will allow you to filter out the incorrect classification data!

3, friendly time expression method

The custom friendly time function has been used before. A few days ago it was found that omnipotent Yii has provided friendly time access, the code is as follows:

Yii:: $app->formatter->asrelativetime (' 1447565922 '); 2 hours ago

4. Use different response types or custom response types

Valid formats:

Format_raw

Format_html

Format_json

Format_jsonp

Format_xml

JSON response

Public Function Actionindex ()

{

\yii:: $app->response->format = \yii\web\response::format_json;

$items = [' Some ', ' array ', ' of ', ' data ' = [' associative ', ' array ']];

return $items;

}

Return:

{

"0": "some",

"1": "Array",

"2": "of",

"Data": ["Associative", "array"]

}

Custom response Format

Let's create a custom response format. Example do something interesting and crazy I return to the PHP array. First, we need to format the program itself. Create components/phparrayformatter.php:

<?phpnamespace App\components;use Yii\helpers\vardumper;use Yii\web\responseformatterinterface;class Phparrayformatter Implements Responseformatterinterface

{

Public function Format ($response)

{

$response->getheaders ()->set (' Content-type ', ' text/php; Charset=utf-8 ');

if ($response->data!== null) {

$response->content = "<?php\nreturn". Vardumper::export ($response->data). "; \ n";

}

}

}

Component configuration:

return [

// ...

' Components ' = [

// ...

' Response ' = [

' Formatters ' = [

' php ' = ' app\components\phparrayformatter ',

],

],

],

];

Now is ready to use. Create a new method Actiontest in Controllers/sitecontroller:

Public Function Actiontest ()

{

Yii:: $app->response->format = ' php ';

return [

' Hello ' = ' world! ',

];

}

Return as follows:

<?phpreturn [

' Hello ' = ' world! ',

];

5, AR storage before the time by the model rewrite behaviors method to achieve elegant storage way.

As follows:

Public Function Behaviors ()

{

return [

' Timestamp ' = [

' Class ' = Timestampbehavior::classname (),

' Attributes ' = [

Activerecord::event_before_insert = ' Creation_time ',

activerecord::event_before_update = ' Update_time ',

],

' Value ' = function () {return date (' U ');//Unix Timestamp},

],

];

}

6, in addition to configuring components to record different levels of log, you can also customize the log log in a place

Use Yii\log\logger;

\yii::getlogger ()->log (' User has been created ', logger::level_info);

7. ActiveForm class does not allow label labels to be generated

Method one, through the ActiveForm class

$form->field ($model, ' field name ')->passwordinput ([' maxlength ' = True])->label (false)?>

Method Two, through the HTML class

Html::activeinput ($type, $model, ' field name ')

Yii2 give the required fields a star, the style is as follows:

Div.required Label:after {

Content: "*";

color:red;

}

Original from: Blog Park/sandea

7 commonly used YII skills knowledge

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.