集合都是「可宏扩展」(macroable) 的,它允许你在执行时将其它方法添加到 Collection 类。例如,通过下面的代码在 Collection 类中添加一个 toUpper 方法:
use Illuminate\Support\Collection;use Illuminate\Support\Str;Collection::macro('toUpper', function () {return $this->map(function ($value) {return Str::upper($value);});});$collection = collect(['first', 'second']);$upper = $collection->toUpper();// ['FIRST', 'SECOND']
use一下db类 QueryBulider
php artisan make:provider DBServiceProvider
<?phpnamespace App\Providers;use Illuminate\Support\ServiceProvider;use Illuminate\Database\Query\Builder as QueryBuilder;class DBServiceProvider extends ServiceProvider{/*** Register services.** @return void*/public function register(){//}/*** Bootstrap services.** @return void*/public function boot(){QueryBuilder::macro('lists',function(){$data = $this->get()->toArray();$res = [];foreach ($data as $val) {$res[] = (array)$val;}return $res;});}}
然后需要去注册一下
打开 config/app.php文件 找到providers
在最后面添加一条
// 扩展DBServiceProviderApp\Providers\DBServiceProvider::class,
这样就可以正常调用了
关于扩展需要注意的地方
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号