玩转 Laravel Helpers

在使用 Laravel 函数时,咱们都避免不了使用其提供的各类各样的全局函数,也称为辅助函数。php

主要集中为处理数组、文件路径、路由和字符串等。html

今天主要说说我喜欢的几个经常使用 Helper 函数,以及 Helpers 实现原理,最后依葫芦画瓢,自定义咱们本身的全局函数。laravel

4 个好玩的 Helpers 函数

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 foundjson

data_get() 函数利用“.”符号,从嵌套数组或者对象中检索数值,其中第三个参数是设置默认值,当检索健不存在时。数组

$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

复制代码

在多级嵌套中,并非每级 key 值都一致,对于同级不一样 key 值,可使用通配符 (*) 代替,如:闭包

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

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


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

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

复制代码

str_plural()

对于我这英语很差的人来讲,如何将单数形式写成复数形式,有时候就会闹出笑话了,但使用 str_plural() 方法,那就便捷多了,其中第二个参数是数值,若是大于 1 时,则转为复数形式,不然仍是单数形式。composer

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
复制代码

同时也有复数转单数函数:str_singular()框架

value() and with()

value() 函数根据传入的值,返回数据,若是,传入的是闭包函数,则会直接运行闭包函数,返回结果:函数

$result = value(5);
// 5

$result = value(function () {
    return false;
});
// false
复制代码

value() 我的以为,更多用在于高阶函数中,闭包函数做为高阶函数的传值传入;

和 value() 相比,能够利用 with() 函数传入参数值:

$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
复制代码

tap()

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

复制代码

传入 value 值,并对 value 值进行操做,最后再返回 value。tap 函数就好将 value 值进行镀金,修改 value 对象的状态和属性,最后返回结果能够进行后续操做。如:

<?php
return tap($user)->update([
    'name' => $name,
    'age' => $age,
]);
复制代码

当咱们传入一个 $user model 到 tap 方法后,咱们就能够链式各类 Model 函数,正常状况下,update 方法返回的是 boolean 类型,正由于咱们用了 tap 函数,update 方法返回的是 user model 对象,能够继续链式 Model 方法,操做 user 模型对象。

其它

更多全局 Helpers 函数,参见: laravel.com/docs/5.6/he…

Helpers 函数实现原理

当咱们在使用这些函数时,印入脑子里的第一个问题就是:Laravel 是怎么实现的?

因此咱们须要从 Laravel 框架源代码入手。

在 PhpStorm IDE 转到这些全局函数定义时,发现主要集中在这两个文件中:

"src/Illuminate/Foundation/helpers.php",
            
"src/Illuminate/Support/helpers.php"
复制代码

由于这些函数并非定义在对象中,而要达到全局加载的目标,Laravel 经过 Composer autoload 加载的方式载入:

引自:docs.phpcomposer.com/04-schema.h…

Files

若是你想要明确的指定,在每次请求时都要载入某些文件,那么你可使用 'files' autoloading。一般做为函数库的载入方式(而非类库)。

实例

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}
复制代码

接下来咱们看看其中一个函数是怎么写的:

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;
    }
}
复制代码

能够看出,每一个函数都是以这种格式的:

if (! function_exists('xxx')) {
    function xxx() {
        // ...
    }
}
复制代码

注: 从 tap 函数源代码能够看出,不管传入的闭包函数有没有返回值,函数返回的值,都是 $value,和传入的值同样,这样也就达到「链式编程」的目标。

自定义 Helpers 函数

若是以上 Helpers 函数还知足不了你的话,咱们就能够经过上文的方式来自定义 Helpers 函数,来知足咱们本身的开发需求。

主要有如下几步:

  1. 在项目中建立 helper.php 文件
  2. 在 composer.json 中将 helper 文件 autoload 载入
  3. composer dump-autoload
  4. 在 helper.php 文件写入咱们的全局函数
  5. test

举个栗子 🔽

总结

学习 Laravel Helpers 实现原理,不只有助于咱们理解和使用这些 Helpers 方法,而且,经过研究每个 Helper 函数是怎么写的,也有助于规范咱们代码逻辑和思惟。学其之所长。

参考:

  1. laravel.com/docs/5.6/he…
  2. laravel-news.com/creating-he…
相关文章
相关标签/搜索