L02 Laravel 教程 - Web 开发实战进阶 学习打卡 Laravel9

1. 主要学习commands如何写, 还有命令的定时任务如何执行

创建command文件

php artisan make:command 文件名 --command=命令名称

要在linux 的定时任务写写上这个,这样linux会每时每刻调用这个命令

 * * * * * php 项目路径/artisan schedule:run >> /dev/null 2>&1

然后将你调用的命令写在/app/Console/Kernel.php

class Kernel extends ConsoleKernel
{
.
.
.
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('larabbs:calculate-active-user')->hourly();
        $schedule->command('larabbs:sync-user-actived-at')->dailyAt('00:00');
    }
    .
    .
    .

2. 学习中间件

创建中间件

php artisan make:middleware 中间件名称

中间件分前置和后置

    public function handle(Request $request, Closure $next)
    {
        /**
        * 写在这里是前置中间件
        */
        return $next($request);
    }

    public function handle(Request $request, Closure $next)
    {
        $request = $next($request);
        /**
        * 代码写在这里是后置中间件
        */
        return $request;
    }

中间件写完以后要配置在/laravel9_l2/app/Http/Kernel.php, 配置主要分为三块全局中间件配置, 中间组配置(给局部的路由配置), 路由别名配置

<?php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * 全局中间件
     */
    protected $middleware = [

    ];

    /**
     * 局部中间件配置
     */
    protected $middlewareGroups = [
        'web' => [

        ],

        'api' => [

        ],
    ];

    /**
     * 定义中间件别名
     */
    protected $routeMiddleware = [

    ];
}

3.学习observe 模型观察者

创建观察者

php artisan make:observer 你要观察的模型名称+Observer

都能观察模型的那些操作呢

creating        创建中
created         创建完毕
updating        更新中
updated         更新完毕
saving,         保存中
saved,          保存
deleting,       删除中
deleted,        删除
restoring,      恢复中
restored        恢复

当你观察模型的操作写出了对应的代码不要忘记在laravel9_l2/app/Providers/AppServiceProvider.php 配置以下, 进行模型和模型观察着的关联, 可以理解为结婚登记, 不能光写不登记要不然不行的

<?php
.
.
.
class AppServiceProvider extends ServiceProvider
{
.
.
.

    public function boot()
    {
        \App\Models\User::observe(\App\Observers\UserObserver::class);
    }
}

4.学习队列

安装包主要用于连接redis 数据库

$ composer require  "predis/predis:~1.1"

.env中配置

.
.
.
QUEUE_CONNECTION=redis
REDIS_CLIENT=predis
.
.
.

如果你是用过 php artisan migrate 请检查有没有 failed_jobs 表 如果没有执行 php artisan migrate

创建队列任务

php artisan make:job 任务名称

编辑队列任务

<?php
.
.
.
class TranslateSlug implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $topic;

    public function __construct($data)
    {
        //构造方法有什么数据可以先从这里创建
        $this->data = $data;
    }

    public function handle()
    {
        //将你的逻辑代码写在这里
    }
}

任务写好后,如何在其他代码逻辑中使用任务

.
.
.
 dispatch(new \App\Jobs\队列任务($data));        //实例化你的队列任务传入需要的数据

进行队列监听

php artisan queue:listen

查看队列任务仪表盘,安装包

composer require "laravel/horizon:~5.9"

php artisan vendor:publish --provider="Laravel\Horizon\HorizonServiceProvider"  //发布服务资源
php artisan horizon   //使用这个命令进行队列监听 可以不使用php artisan queue:listen

可以对horizon的访问权限进行配置

<?php

namespace App\Providers;
.
.
.
use Laravel\Horizon\Horizon;

class AuthServiceProvider extends ServiceProvider
{
    .
    .
    .
    public function boot()
    {
        $this->registerPolicies();

        Horizon::auth(function ($request) {
            //在这里可以写代码逻辑, 可以获取访问的用户的权限,或者路由中参数进行判断
            //如果return true 就可以访问
        });

    }
}

5.学习policies 策略文件

创建policies文件

php artisan make:policy 政策文件

编辑policies 策略文件

<?php
namespace App\Policies;
.
.
.
class TopicPolicy extends Policy
{
    public function update(User $user, Model $model)
    {
        //这里可以写模型数据之间的判断如果为true 就成
    }
}

别忘将你的将的策略文件在服务中配置一下app/Providers/AuthServiceProvider.php

<?php
namespace App\Providers;
.
.
.
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
         \App\Models\Topic::class => \App\Policies\TopicPolicy::class,
    ];
.
.
.
}

配置好了就可以使用了

    {{在视图层中使用}}
    @can('update', $topic)   <span>如果通过就显示</span>   @endcan

    //在控制器中使用
    $this->authorize('update', $topic);

    //通过Request 
    $request->user()->cannot('create', Post::class)

6.学习事件和监听

创建事件和监听

php artisan make:event TestEvent                                #创建一个事件
php artisan make:listener TestListener --event=TestEvent        #根据事件创建监听 --event 代表绑定的事件

app/Providers/EventServiceProvider.php 配置一下事件和监听的关联,一个事件可以有多个监听

<?php
namespace App\Providers;
.
.
.
class EventServiceProvider extends ServiceProvider
{
.
.
.
    protected $listen = [
    .
    .
    .
        \App\Events\TestEvent::class=>[
            \App\Listeners\TestListener::class,
            \App\Listeners\Test2Listener::class
        ]
    ];
.
.
.
}

7.学习 Notifications 通知

创建通知文件

php artisan make:notification TestNotification

如何写编写通知

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class TestNotification extends Notification implements ShouldQueue  #implements ShouldQueue 代表使用了队列
{
    use Queueable;

    public $model;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(Model $model)
    {
        //在这里可以初始化你的一些数据
        $this->model = $model;
    }


    /**
     * 写好的方法要在这里注册一下才行, 把前面的to去掉 
     * 你也可以定义一下其他的通知方法如 toData toWeb ToHe 等
     * 
     * @param $notifiable
     * @return string[]
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * 邮件通知的方法
     * @param $notifiable
     * @return MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }
}

如何使用 ,可以在App\Models\User 中使用Notifiable 这个 trait

<?php

namespace App\Models;

.
.
.
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable,;
    .
    .
    .

然后再控制器中使用,或者在代码其他部位使用

$user->notify(new \App\Notifications\TestNotification($model));

8.学习 MySql 外键约束 之CASCADE、SET NULL、RESTRICT、NO ACTION分析和作用

CASCADE
在父表上update/delete记录时,同步update/delete掉子表的匹配记录

SET NULL
在父表上update/delete记录时,将子表上匹配记录的列设为null (要注意子表的外键列不能为not null)

NO ACTION
如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作

RESTRICT
同no action, 都是立即检查外键约束

SET NULL
父表有变更时,子表将外键列设置成一个默认的值 但Innodb不能识别

.
.
.
    public function up()
    {
        //这里使用CASCADE
        Schema::table('topics', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });


        Schema::table('replies', function (Blueprint $table) {

            // 当 user_id 对应的 users 表数据被删除时,删除此条数据
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            // 当 topic_id 对应的 topics 表数据被删除时,删除此条数据
            $table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
        });
        .
        .
        .
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!