Laravel宏指令Macro使用

宏指令允许添加自定义功能到 Laravel 的内部组件里去,App\Providers\AppServiceProvider boot()方法中注册。

Request

#注册
Request::macro('introduce', function ($name) {
    return 'Hello ' . $name . '!';
});

#使用
dump(Request::introduce('lily')); // "Hello lily!"
dump(request()->introduce('lily')); // "Hello lily!" 

 Response

#注册
\Illuminate\Support\Facades\Response::macro('success', function ($data = [], $message = 'success') {
    return new \Illuminate\Http\JsonResponse([
        'code' => 0,
        'data' => $data,
        'message' => $message
    ], 200);
});

#使用
return response()->success(['a' => 1], 'success'); //{"code":0,"data":{"a":1},"message":"success"}

 Builder 

#注册
\Illuminate\Database\Query\Builder::macro('whenFlagMatches', function ($flag, $callback) {
    if ($flag) {
        call_user_func($callback->bindTo($this));
    }
    return $this;
});

\Illuminate\Database\Query\Builder::macro('toRawSql', function () {
    return array_reduce($this->getBindings(), function ($sql, $binding) {
        return preg_replace('/\?/', is_numeric($binding) ? $binding : "'" . $binding . "'", $sql, 1);
    }, $this->toSql());
});

\Illuminate\Database\Eloquent\Builder::macro('toRawSql', function () {
    return ($this->getQuery()->toRawSql());
});


#使用
$is_super = true;
$query = Post::whenFlagMatches($is_super, function () {
  $this->where('id', '=', 5);
});
$query2 = DB::connection()->table('posts')->whenFlagMatches($is_super, function () {
  $this->where('id', '=', 5);
});
dump($query->toRawSql());   //select * from `posts` where `id` = 5
dump($query2->toRawSql()); //select * from `posts` where `id` = 5
dump($query->get()->toArray()); //得到的结果为纯php数组形式
dump($query2->get()->toArray());//得到的结果为元素为对象的数组

Collection

#注册
\Illuminate\Support\Collection::macro('toUpper', function () {
    return $this->map(function ($value) {
        return \Illuminate\Support\Str::upper($value);
    });
});

\Illuminate\Support\Collection::macro('toLocale', function ($locale) {
    return $this->map(function ($value) use ($locale) {
        return \Illuminate\Support\Facades\Lang::get($value, [], $locale);
    });
});

#使用
$collection = collect(['Name', 'Email']);
dump($collection->toUpper()->toArray()); // ['NAME','EMAIL']
$collection = collect(['label.Name', 'label.Email']);
$translated = $collection->toLocale('zh_CN');
dump($translated->toArray());// ['用户名','电子邮箱']

#toLocale需要预先在resources/lang/zh_CN/label.php放如以下内容
return [
    'Name'=>'用户名',
    'Email'=>'电子邮箱',
];

 

 

 

 

 

 

posted @ 2022-11-19 10:43  carol2014  阅读(328)  评论(0编辑  收藏  举报