Laravel学习笔记

本文介绍了Laravel框架中的懒加载机制,通过日志懒加载和Model数据加载举例说明其优势。此外,详细阐述了如何设置定时任务,包括使用call方法和Command命令,并给出了配置及执行示例。同时,还涉及到了消息通知、数据集合的计算与过滤操作,展示了Laravel在提升效率和代码优雅性方面的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

懒加载

参考文档: https://laravel.com/docs/6.x/releases

懒加载和传统加载的区别:传统的数据加载是一下把所有的数据加载起来,给数据库和内存造成很大压力,如果一个人访问还好说,上千上万人呢。而懒加载是一直在加载数据,如果加载的数据过多的话,可能会稍微慢点,但是极大地减轻了数据库的压力。

日志懒加载

  • 主要使用LazyCollection加上一个闭包函数,一行一行的处理数据
  • chunk是分块处理数据,下面的chunk(4)是指每次处理4条数据,chunk中也可以使用闭包函数,在闭包函数中写怎么处理这几条数据
  • map是对查询结果进行处理,相当于get之后进行foreach
  • each方法是对数据进行分析
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方法

  1. /app/Console/Kernel.php中有个schedule方法,意思是每分钟写入一条日志信息
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function(){
            Log::info('test');
        })->everyMinute();
    }
    
  2. 运行php artisan schedule:run是运行一次才执行一次上边那个方法,咱们要做的是让系统自动执行,所以要用到linux的crontab
    具体实现办法:
    (1) 查看项目路径
    pwd
    
    (2) 将定时任务写入task.txt中,这个是每分钟执行一次,如果是每小时执行等的情况,请参考Linux下设置/查看/取消定时任务
    echo '* * * * * cd /var/www/html/English.test/&& php artisan schedule:run >> /dev/null 2>&1' > task.txt
    
    (3) 然后执行下面的命令
    crontab task.txt
    crontab -l
    
    (4) 结束定时任务
    crontab -r
    

使用Command命令

当逻辑较为简单时使用call方法较为简单,但是逻辑稍微复杂的时候,会使schedule方法变得很臃肿

  1. 创建command,文件存储在/app/Console/Commands
    php artisan make:command Test
    
  2. 修改/app/Console/Commands/Test.php
    //给command其一个名字
    protected $signature = 'message:test';
    
    //$description可以不改,是对$signature的描述
    
    //主要逻辑在handle函数中
    public function handle(){
    	Log::info('早上好');
    }
    
  3. 调用刚刚创建的Command
    //在/app/Console/Kernel.php文件中
    //withoutOverlapping()是防止任务重叠的,最好加上
    protected function schedule(Schedule $schedule){
    	$schedule->command('message:test')
    			 ->everyMinute()
    			 ->withoutOverlapping();
    }
    

消息通知

参考文档:https://laravel.com/docs/6.x/notifications

  1. 使用php artisan make:notification InvoicePaid生成消息通知,InvoicePaid可自定义
  2. 配置/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
            ];
    }
    
  3. 创建表
    php artisan notifications:table
    php artisan migrate
    
  4. 在控制器中调用
    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'));
    }
    
  5. 在视图显示
    @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
    

数据集合

可以消除大量不必要的判断,使代码更加优雅

数据计算

  1. 计算最小值 $data->min('price');
  2. 计算最大值 $data->max('price');
  3. 计算平均值 $data->average('price');
  4. 计算总和 $data->sum('price');
  5. 计算中位数 $data->median('price');
  6. 也可以在闭包函数中使用,意思是取价格*折扣的最小值
    $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'];
});

其他的

  1. dump()可以将每一步的执行结果显示出来,如
    $data->filter(function($item){
    	return $item['online'];
    })->dump()
    ->min(function($item){
    	return $item['price']*$item['discount'];
    });
    
  2. reverse()可以将结果逆序排列
  3. chunk()
  4. map()里的匿名方法是对查询结果进行处理
    比如:没有使用map之前是这样的
    $data = model::query()->where(xxx)->get();
    foreach($data as &$item) {
    	...
    }
    
    用了map之后是这样的
    $data = model::query()->where(xxx)->get()->map(function($item) {
    	$item[xx] = xxx;
    	return $item;
    });
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值