Tips: It takes 5-10 minutes to read.

demand

The problem is that when the API returns data, the front end doesn’t know what the type or status field means. The previous way to do this is to use the if process statement. Manually convert status=1 to “enabled” and status=2 to “disabled” (this is what I did when I first started).

Is that complicated? Since it is complex, we can improve it by adding a type_str description field to indicate what the number in type means, and in the same way we can equip status with a status_str. Ok, we have a solution, but it’s not convenient to add it directly to the database, so we need to use helpers.php.

Detailed implementation steps

Create the PHP

This is a custom constant configuration file in the config/constants.php path where we define our constants:

<? phpreturn [
    'APP_NAME'= >'my project'.'APP_URL'= >'Your domain name'.'USER_TYPE'= > [1 = >'Agent', 2 = >'Distributor', 3 = >'Regular User',].Copy the code

As you can see, I’ve defined a constant called USER_TYPE, and I’ll explain why it’s called that.

Configure the helpers.php file

First create our helper class file and edit itapp/helpers.php:
<? phpif(! function_exists('constants')) {
        function constants(string $constName.$trans = false) {

            $config = config('constants.' . strtoupper($constName));

            if ($trans= = =false) {
                return $config;
            }
            if ($trans= = ='label') {
                return array2label($config); }}}if(! function_exists('array2label')) {
        function array2label(array $arr) {
            $ret = [];

            foreach ($arr as $key= >$item) {
                $ret[] = ['label'= >$item.'value'= >$key];
            }
            return $ret; }}Copy the code

To explain a little bit, I’ve defined one of the constants functions here, which is to take the corresponding values from the constants configuration file through the config helper function when we pass in parameters. The full flow will be explained at the end.

Add helpers.php to the auto-loading of Composer
// Add files toautoloadIn the"autoload": {
        "files": [
            "app/helpers.php",]."classmap": [
            "app/Libraries"."database/seeds"."database/factories"]."psr-4": {
            "App\\": "app/"}},Copy the code
Finally execute the command
composer dump-autoload
Copy the code

Append fields to the Model Model

This is where the basic configuration ends. We append the type_str field to the Model.

protected $appends = ['type_str'];
Copy the code

Then “append” type_str to the json value of the document:

public function getTypeStrAttribute()
    {
        return array_get(constants( 'USER_TYPE'), $this->getAttribute('type'));
    }
Copy the code

We’re calling the constants function we defined earlier in helpers.php, and the array_get method uses the “. “sign to get the value from the nested array, not necessarily array_GET, but something else.

Continue to refine and use traits for code reuse

At the previous step, our needs are basically fulfilled. However, I have about 10 tables in a project that use the type and status fields, and writing a piece of code like this in each model doesn’t quite fit the concept of elegance, so I used traits in the refinement process.

For details on traits, which are a code reuse mechanism for single-inheritance languages like PHP, see the PHP documentation.

Create the trait file and edit it

Path in the app/Traits/TypeTrait. PHP

<? php namespace App\Traits; trait TypeTrait { publicfunction getTypeStrAttribute()
    {
        return array_get(constants(class_basename(static::class) . '_TYPE'), $this->getAttribute('type')); }}Copy the code
Use traits

Append (); append (); append ();

 use TypeTrait;
 
 protected $appends = ['type_str'];
Copy the code

Remember why the hole was called USER_TYPE? Class_basename returns the name of the given class in the deleted namespace. For example, in the UESR model it returns user, which makes it easier to reuse code.

Complete steps

For those of you who are still confused by this, you’ve been talking about how this works. Let’s go through the process together (in code) :

  1. The User controller calls the query method, using toArray() to return the fields required by the interface.

  2. When querying data through the User model, we append the type_str field. This field is not existing in the data table, but we add it temporarily, so we need to define its value.

  3. The User model then calls the getTypeStrAttribute() method in TypeTrait. PHP, which is nested in three layers:

    Class_basename returns the name of the class in which the namespace is deleted for the given class. The string is concatenated, and the result is User_TYPE.

    3.2 In the middle layer, the Constants function receives our parameter “User_TYPE”, strtoupper converts “User_TYPE” to all uppercase characters, and values it in the custom constant configuration file constants.php via config, Returns an array of USER_TYPE.

    3.3 Go back to getTypeStrAttribute(). The outermost layer matches the description of the type field with array_GET and returns,

  4. This assignment to the appended field succeeds.

Conclusion: it took two hours to complete, and it has been revised for three times. There may still be some minor flaws. If there are any problems, please comment and correct them, or you can correct them!