When using Laravel functions, we can’t avoid using the various global functions, also known as helper functions.

It mainly deals with arrays, file paths, routes and strings.

Helpers Helpers Helpers Helpers Helpers Helpers Helpers Helpers Helpers Helpers

Four Helpers that are fun

data_get()

The data_get function retrieves a value from a nested array or object using “dot” notation:

The data_get function also accepts a default value, which will be returned if the specified key is not found

The data_get() function utilizes “. Symbol to retrieve a value from a nested array or object, where the third argument is set to the default value if the key does not exist.

$array = ['albums'= > ['rock'= > ['count'= >75]]];

$count = data_get($array, 'albums.rock.count'); 
/ / 75

$avgCost = data_get($array, 'albums.rock.avg_cost'.0); 
/ / 0

$object->albums->rock->count = 75;

$count = data_get($object, 'albums.rock.count'); 
/ / 75

$avgCost = data_get($object, 'albums.rock.avg_cost'.0); 
/ / 0

Copy the code

In multi-level nesting, not all key values at each level are the same. For different key values at the same level, wildcard characters (*) can be used instead, for example:

$array = ['albums'= > ['rock'= > ['count'= >75].'punk'= > ['count'= >12]]];

$counts = data_get($array, 'albums.*.count');
/ / [12] 75,


$array = ['albums'= > ['rock'.'punk'= > ['count'= >12]]];

$counts = data_get($array, 'albums.*.count');
// [NULL, 12]

Copy the code

str_plural()

For me, who doesn’t speak English well, writing singular forms into plural forms can sometimes be a source of jokes, but it’s much easier to use str_plural(), where the second argument is a number, plural if greater than 1, singular otherwise.

str_plural('dog'); // dogs
str_plural('cat'); // cats

str_plural('dog'.2); // dogs
str_plural('cat'.1); // cat

str_plural('child'); // children
str_plural('person'); // people
str_plural('fish'); // fish
str_plural('deer'.2); // deer

str_singular('children') // child
Copy the code

There’s also a plural convert to singular function: str_singular()

value() and with()

The value() function returns data based on the value passed in. If the closure function is passed in, the closure function is run directly and returns:

$result = value(5);
/ / 5

$result = value(function (a) {
    return false;
});
// false
Copy the code

In my opinion, value() is more used in higher-order functions. Closure functions are passed in as values of higher-order functions.

Instead of value(), we can use the with() function to pass in parameter values:

$callback = function ($value) {
    return (is_numeric($value)) ? $value * 2 : 0;
};

$result = with(5, $callback);

/ / 10

$result = with(null, $callback);

/ / 0

$result = with(5.null);

/ / 5
Copy the code

tap()


      
function tap($value, $callback)
{
    $callback($value);
    return $value;
}

Copy the code

The value is passed in, the value is manipulated, and the value is returned. The tap function gold-plates the value, modifies the state and properties of the value object, and returns the result for subsequent operations. Such as:


      
return tap($user)->update([
    'name' => $name,
    'age' => $age,
]);
Copy the code

When we pass a $user model to the tap method, we can chain various model functions. Normally, the update method returns a Boolean type, and because we are using the tap function, The update method returns a User model object. You can continue the chained model method and manipulate the User model object.

other

For more information about Helpers functions, see laravel.com/docs/5.6/he…

Helpers function implementation principle

When we use these functions, the first question that comes to mind is: How does Laravel implement it?

So we need to start with the Laravel framework source code.

When PhpStorm IDE goes to these global function definitions, it is found that they are mainly concentrated in these two files:

"src/Illuminate/Foundation/helpers.php"."src/Illuminate/Support/helpers.php"
Copy the code

Because these functions are not defined in objects, to achieve the goal of global loading, Laravel loads them in Composer Autoload:

Quote: docs.phpcomposer.com/04-schema.h…

Files

If you want to explicitly specify that certain files are to be loaded on each request, you can use ‘files’ Autoloading. Usually loaded as a function library (not a class library).

The instance

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]}}Copy the code

Let’s see how one of these functions is written:

if (! function_exists('tap')) {
    /**
     * Call the given Closure with the given value then return the value.
     *
     * @param  mixed  $value
     * @param  callable|null  $callback
     * @return mixed
     */
    function tap($value, $callback = null)
    {
        if (is_null($callback)) {
            return new HigherOrderTapProxy($value);
        }

        $callback($value);

        return$value; }}Copy the code

As you can see, each function is in this format:

if (! function_exists('xxx')) {
    function xxx(a) {
        // ...}}Copy the code

The tap function returns $value regardless of whether or not the closure function returns a value, which is the same as the value passed in.

Customize Helpers functions

If the above Helpers function is not enough for you, we can customize Helpers function in the above way to meet our own development needs.

There are mainly the following steps:

  1. Create helper.php files in your project
  2. Load the helper file Autoload in composer. Json
  3. composer dump-autoload
  4. Write our global function in helper.php
  5. test

For example, 🔽

conclusion

Learning how Laravel Helpers are implemented not only helps us understand and use these Helpers methods, but also helps us to standardize our code logic and thinking by studying how each Helper function is written. Learn what they are good at.

Reference:

  1. Laravel.com/docs/5.6/he…
  2. Laravel-news.com/creating-he…