php notes of the 05-tp5 get with modifier

Acquirer

Naming convention is:

getFieldNameAttr

For example, we need to state the value of the conversion, you can use:

 

<? PHP
 class the User the extends the Model 
{ 
    public  function getStatusAttr ( $ value ) 
    { 
        $ Status = [-1 => 'delete', 0 => 'disabled', 1 => 'normal', 2 => 'Pending' ] ;
         return  $ Status [ $ value ]; 
    } 
}

 

User $ = the User :: GET (. 1 );
 echo  $ User -> Status; // example outputs "normal"

If you define the case of an acquirer, hoping for a data sheet of the original data, you can use:

User $ = the User :: GET (. 1 );
 // acquired by the acquirer field 
echo  $ User -> Status;
 // get the raw data field 
echo  $ User -> the getData ( 'Status' );
 // Get all of the original data 
dump ( $ the User -> getData ());

 

Model Setup

 

The controller may be further provided in ( withAttrmethod can be called multiple times to obtain a plurality of fields is defined.)

Db::name('user')->withAttr('name', function($value, $data) {
    return strtolower($value);
})->select();

modifier

And acquirer contrast, the main role is to modify the device data object model values ​​set for processing.

Naming method as modifier: SET FieldName the Attr

Scenario:

Modifier usage scenarios the like and the reader:

  • Conversion time date field is written;
  • Enumeration type set or written;
  • Fields into the digital state;
  • It relates to a field of other fields or combinations of writing conditions
//模型设置
<?php class User extends Model { public function setNameAttr($value) { return strtolower($value); } }

Save name to the database when it will lowercase.

In addition to assignments of 2- embodiment may trigger modifier, the following method can also be used to trigger a batch modifier:

$user = new User();
$data['name'] = 'THINKPHP';
$data['email'] = '[email protected]';
$user->data($data, true);
$user->save();
echo $user->name; // thinkphp

If nameand emailfields are defined modifier, it will be handled.

Method 3 using the save method to trigger, for example:

$user = new User();
$data['name'] = 'THINKPHP';
$data['email'] = '[email protected]';
$user->save($data);
echo $user->name; // thinkphp

Note: The method modifier only effective method of writing the model, the database write writing method call is invalid , for example, modify the following is not valid.

$user = new User();
$data['name'] = 'THINKPHP';
$data['email'] = '[email protected]';
$user->insert($data);

 

Guess you like

Origin www.cnblogs.com/somethingWithiOS/p/11966615.html