懒加载
参考文档: https://laravel.com/docs/6.x/releases
懒加载和传统加载的区别:传统的数据加载是一下把所有的数据加载起来,给数据库和内存造成很大压力,如果一个人访问还好说,上千上万人呢。而懒加载是一直在加载数据,如果加载的数据过多的话,可能会稍微慢点,但是极大地减轻了数据库的压力。
日志懒加载
- 主要使用LazyCollection加上一个闭包函数,一行一行的处理数据
chunk
是分块处理数据,下面的chunk(4)
是指每次处理4条数据,chunk
中也可以使用闭包函数,在闭包函数中写怎么处理这几条数据map
是对查询结果进行处理,相当于get之后进行foreacheach
方法是对数据进行分析
use App\LogEntry;
use Illuminate\Support\LazyCollection;
LazyCollection::make(function () {
$handle = fopen('log.txt', 'r');
while (($line = fgets($handle)) !== false) {
yield $line;
}
})
->chunk(4)
->map(function ($lines) {
return LogEntry::fromLines($lines);
})
->each(function (LogEntry $logEntry) {
// Process the log entry...
});
加载Model数据
- 调用
cursor
方法就会调用懒加载机制获取数据
原来的
$users = App\User::all()->filter(function ($user) {
return $user->id > 500;
});
使用懒加载之后
$users = App\User::cursor()->filter(function ($user) {
return $user->id > 500;
});
定时任务
使用场景:比如每天早上提醒用户啥啥啥
参考文档:https://laravel.com/docs/6.x/scheduling
使用call方法
- 在
/app/Console/Kernel.php
中有个schedule
方法,意思是每分钟写入一条日志信息protected function schedule(Schedule $schedule) { $schedule->call(function(){ Log::info('test'); })->everyMinute(); }
- 运行
php artisan schedule:run
是运行一次才执行一次上边那个方法,咱们要做的是让系统自动执行,所以要用到linux的crontab
具体实现办法:
(1) 查看项目路径
(2) 将定时任务写入task.txt中,这个是每分钟执行一次,如果是每小时执行等的情况,请参考Linux下设置/查看/取消定时任务pwd
(3) 然后执行下面的命令echo '* * * * * cd /var/www/html/English.test/&& php artisan schedule:run >> /dev/null 2>&1' > task.txt
(4) 结束定时任务crontab task.txt crontab -l
crontab -r
使用Command命令
当逻辑较为简单时使用call方法较为简单,但是逻辑稍微复杂的时候,会使schedule
方法变得很臃肿
- 创建command,文件存储在
/app/Console/Commands
中php artisan make:command Test
- 修改
/app/Console/Commands/Test.php
//给command其一个名字 protected $signature = 'message:test'; //$description可以不改,是对$signature的描述 //主要逻辑在handle函数中 public function handle(){ Log::info('早上好'); }
- 调用刚刚创建的Command
//在/app/Console/Kernel.php文件中 //withoutOverlapping()是防止任务重叠的,最好加上 protected function schedule(Schedule $schedule){ $schedule->command('message:test') ->everyMinute() ->withoutOverlapping(); }
消息通知
参考文档:https://laravel.com/docs/6.x/notifications
- 使用
php artisan make:notification InvoicePaid
生成消息通知,InvoicePaid
可自定义 - 配置
/app/Notifications/InvoicePaid.php
,其他的通知类型在文档中都有,这里以database为例public $content; /** * Create a new notification instance. * * @return void */ public function __construct($content) { $this->content = $content; } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['database']; } public function toDatabase($notifiable) { return [ 'uid'=>99, 'money'=>'$100', 'content'=>$this->content ]; }
- 创建表
php artisan notifications:table php artisan migrate
- 在控制器中调用
use App\Notifications\InvoicePaid; use Illuminate\Support\Facades\Notification; //给管理员和当前登录用户发送消息 public function sendNotice(){ $user = User::join('roles','users.id','=','roles.user_id') ->where('users.id',Auth::id()) ->orWhere('roles.role','管理员') ->get(); Notification::send($user, new TeacherNotice('消息功能测试')); // $user->notify(new TeacherNotice('消息功能测试')); } //获取当前登录用户的消息 public function show() { $user = User::find(Auth::id()); // foreach ($user->Notifications as $notification) { // dump($notification->data); // } // return $user; return view('test',compact('user')); }
- 在视图显示
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel-body"> @foreach($user->notifications as $notification) <p>{{$notification['data']['content']}}</p> @endforeach </div> </div> </div> </div> @endsection
数据集合
可以消除大量不必要的判断,使代码更加优雅
数据计算
- 计算最小值
$data->min('price');
- 计算最大值
$data->max('price');
- 计算平均值
$data->average('price');
- 计算总和
$data->sum('price');
- 计算中位数
$data->median('price');
- 也可以在闭包函数中使用,意思是取价格*折扣的最小值
$data->min(function($item){ return $item['price']*$item['discount']; });
filter过滤数据
在进行计算前先进行数据过滤
$data->filter(function($item){
return $item['online'];
})->min(function($item){
return $item['price']*$item['discount'];
});
其他的
dump()
可以将每一步的执行结果显示出来,如$data->filter(function($item){ return $item['online']; })->dump() ->min(function($item){ return $item['price']*$item['discount']; });
reverse()
可以将结果逆序排列chunk()
map()
里的匿名方法是对查询结果进行处理
比如:没有使用map之前是这样的
用了map之后是这样的$data = model::query()->where(xxx)->get(); foreach($data as &$item) { ... }
$data = model::query()->where(xxx)->get()->map(function($item) { $item[xx] = xxx; return $item; });