laravel 框架基础 学习整理

一. Laravel 数据库迁移

  1. 创建迁移文件(在database/migrations目录)

php artian make:migration create_table_articles --create=articles

  1. 编写命令行生成的迁移文件

在database/migrations/create_table_articles.php 的up()方法中

ps: up() 运行数据库迁移 down:回滚数据库迁移

    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title',100)->comment("标题");
        $table->string('keywords',18)->comment("关键词");
        $table->string('description',100)->comment("描述");
        $table->string('author',20)->comment("作者");
        $table->text('content')->comment("内容");
        $table->timestamps();
    });
}
  1. 执行迁移文件(会在数据库生成相应的表)
php artisan migrate

php artisan migrate

  1. 回滚操作(回滚最新一次的迁移操作)

php artisan migrate:rollback

  • 回滚所有应用的迁移 (危险操作) php artisan migrate:reset
  • 回滚迁移并运行: php artisan migrate:refresh

​ Ps:此命令先将所有的数据迁移文件进行回滚,然后重新生成迁移;也就是说先删除所有迁移文件中的表,再生成所有迁移文件的表(所有数据将丢失)

  1. 使用迁移文件新增字段

    如果要修改字段属性,千万不要在原来的迁移文件中对字段进行操作

    要修改一个表的字段属性,在laravel中以新增一个迁移文件的形式进行增加和修改

    1. 修改/删除字段

    2. 将doctrine/dbal 依赖添加到composer.json中

      composer require doctrine/dbal

    3. 创建修改迁移文件

      php artisan make:migration alter_users_edit_compony --table=users

      1. 编写migration迁移文件
      Schema::table('users', function (Blueprint $table) {
          //修改compony字段变成user_compomys
          $table->renameColumn('compony','user_componys');
          //修改name字段属性长度变成50
          $table->string('name',50)->change();
          //删除nickname字段
          $table->dropColumn('nickname');
          //创建索引
          $table->index('email');
      });
      
      1. 执行

      php artisan migrate --path=database/migrations/2021_12_22_031201_alter_users_edit_compony.php

      具体参考文章:https://www.cnblogs.com/rianley/p/9518422.html

    二. laravel数据填充

    1. 创建seeder文件
    php artisan make:seeder UsersTableSeeder
    

    执行命令后会在database/seeders目录下生成UsersTableSeeds.php文件;

    1. 编写seeder文件
    public function run()
    {
        //
        DB::table('users')->insert([
            'name'           =>  "王美丽",
            'email'          =>  "kevlin@gmail.com",
            'user_componys'  =>  "tencent",
            'password'       =>  bcrypt('000000'),
            ]);
    }
    
    1. 执行单个数据填充命令

      php artisan db:seed  --class=UsersTableSeeder
      

    进阶:模型工厂

    1.创建模型文件

    php artisan make:model Posts   
    

    此命令会在app/Models目录下生成Goods.php文件

    2.创建模型工厂

    php artisan make:factory PostsFactory
    

    此命令会在database/factories目录下生成对应的工厂文件 PostsFactory.php

    3.编写工厂文件

    public function definition()
    {
        return [
            //
            'uid'     => $this->faker->uuid,
            'title'   => $this->faker->title,
            'content' => $this->faker->text
        ];
    }
    

    4.创建seeder类填充

    php artisan db:seed --class=PostsTableSeeder

    5.编写通过seeder生成的填充文件,在run()方法中调用模型工厂填充数据

    public function run()
    {
        //
        Posts::factory()->count(3)->create();
    }
    

    6.执行填充数据

    php artisan db:seed --class=PostsTableSeeder

    补充:

    php artisan db:seed //执行所有填充文件

三.中间件

1.创建中间件

php artisan make:middleware Testa

在App\Middleware目录生成Testa.php

2.编写中间件 Testa.php

    public function handle(Request $request, Closure $next)
    {
//        //前置中间件
//        if (1){
//            echo "这是前置中间件,在控制器方法执行之前调用";
//        }
//        return $next($request);
        //后置中间件
        $response = $next($request);
        echo "这是后置中间件,在控制器方法执行之后调用";
        return  $response;
        //可以在控制器中使用echo 进行测试中间件的区别(return 不行)
    }
    public function terminate($request, $response){
        // 编写业务逻辑
        echo '结束之后';
    }

3.注册中间件

App/Http/Kernel.php 文件中 $routeMiddleware 数组中添加

'testa'  => \App\Http\Middleware\TestA::class

$middleware 全局中间件,无论执行什么请求都会执行这个数组中的中间件

$middlewareGroups 中间件组

$routeMiddleware 路由中间件

4.使用中间件

Route::get('/testmiddleware','App\Http\Controllers\IndexController@test')->middleware('testa');

发送邮件

Mail::raw("自如初邮件测试内容",function (Message $message){
    $message->to('kevlin.zhang@webpowerchina.com');
    $message->subject("ziruchu主题");
});

自定义模板

在app/Porviders/AppserviceProvider.php的boot方法中编写

Blade::directive('webname',function ($expression){
    return "个人网站";
});

模板中使用示例: @webname();

事件监听者

Laravel事件监听使用观察者模型实现

1.定义路由

Route::get('user/add','App\Http\Controllers\UserController@add');
Route::post('user/store','App\Http\Controllers\UserController@store');

2.编写控制器和视图方法

// app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
   public function add()
   {
       return view('user.add');
   }

   public function store(Request $request)
   {
		$data = $request->except('_token');
        $data['password'] = "1";
        $data['user_componys'] = "user_componys";
        $user = User::create($data);
		//分发事件(触发事件) 先不需要理解,看到后面定义事件再看这里
        event(new UserAdd($user));
        echo "hello";
   }
}
//resources/views/user/add.blade.php
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
</head>
<body>
<form action="{{ url('user/store') }}" method="post">
    @csrf
    用户名:<input type="text" name="name">
    邮箱:<input type="text" name="email">
    <input type="submit" value="提交">
</form>
</body>
</html>

3.定义事件(类)

php artisan make:event UserAdd

修改事件类的构造方法(用于获取事件的相关内容)

// App/Events/UserAdd.php
protected $user ;

public function __construct(User $user){

	$this->user = $user;

}

4.定义事件监听类 (和事件绑定)

php artisan make:listerers UserAddLog.php --event=UserAdd

在handle方法中写具体的业务逻辑

<?php

namespace App\Listeners;

use App\Events\UserAdd;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class UserAddLog
{
    public function __construct()
    {
    }
    public function handle(UserAdd $event)
    {
        // 事件监听者
//        dd($event);
    }
}

5.注册事件监听(在服务提供者中; 初始化应用程序的时候会加载这里面所有的类)

//App/providers/EventServiceProvider.php
 protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        //事件   =>  对应的的时间监听者(可以多个)
        UserAdd::class => [
            UserAddLog::class
        ]
    ];

6.结果

App\Events\UserAdd {#373 ▼
  #user: App\Models\User {#1256 ▼
    #fillable: array:3 [▶]
    #hidden: array:2 [▶]
    #casts: array:1 [▶]
    #dispatchesEvents: array:1 [▶]
    #connection: "mysql"
    #table: "users"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #escapeWhenCastingToString: false
    #attributes: array:6 [▶]
    #original: array:6 [▶]
    #changes: []
    #classCastCache: []
    #dates: []
    #dateFormat: null
    #appends: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #visible: []
    #guarded: array:1 [▶]
    #rememberTokenName: "remember_token"
    #accessToken: null
  }
  +socket: null
}

事件监听订阅者

前四个步骤是一样的,这里从第四步开始

第一步:定义路由

第二步:定义控制器与方法

第三步:创建视图

第四步:创建事件类

第五步:创建事件订阅者(和事件绑定)

php artisan make:listerners UserAddEventSubscribe --event=UserAdd
//App/Listensers/UserAddEventSubscribe.php
<?php
namespace App\Listeners;
use App\Events\UserAdd;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class UserAddEventSubscribe
{
    public function __construct(){}
    public function handle(UserAdd $event){}
    public function handleAddUser($event)
    {
        dd($event);
    }
    public function subscribe($event)
    {
        // 可以用此方式
        $event->listen(
            UserAdd::class,
             UserAddEventSubscribe::class.'@handleAddUser'
        );
        //换种方式
//        return [
//          UserAdd::class => [UserAddEventSubscribe::class,'handleAddUser']
//        ];
    }
}

第六步:注册事件订阅者

//App/providers/EventServiceProvider.php
protected $subscribe = [
    UserEventSubscriber::class,
    UserAddEventSubscribe::class,
];

结果:

App\Events\UserAdd {#375 ▼
  #user: App\Models\User {#1258 ▼
    #fillable: array:3 [▶]
    #hidden: array:2 [▶]
    #casts: array:1 [▶]
    #dispatchesEvents: array:1 [▶]
    #connection: "mysql"
    #table: "users"
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: true
    #escapeWhenCastingToString: false
    #attributes: array:6 [▶]
    #original: array:6 [▶]
    #changes: []
    #classCastCache: []
    #dates: []
    #dateFormat: null
    #appends: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #visible: []
    #guarded: array:1 [▶]
    #rememberTokenName: "remember_token"
    #accessToken: null
  }
  +socket: null
}

队列

1.创建队列

php artisan make:queue SendMailToUser

会在 app/Jobs目录下创建SendEmailToUser.php

修改代码

 	//   App\Jobs\SendEmailToUser.php   
 	public $user;
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function handle()
    {
        //模拟失败的任务处理
//        testFailQueue(); //该函数不存在,因此队列任务执行失败
        //编写自定义业务的逻辑
        Log::info("发送邮件给{$this->user->name}用户成功!");
    }

    public function failed(\Throwable $exception = null)
    {
        Log::error("发送给{$this->user->name}的邮件失败");
    }

2.分发队列(将数据添加到队列中)

dispatch('队列名称(对象)')

在控制器中编写业务逻辑

    //App/Http/Controllers/UserController.php
    public function mysqlQueue()
    {
        $users = User::all();
        foreach ($users as $user){
            dispatch(new SendEmailToUser($user)); //立即分发
//            dispatch(new SendEmailToUser($user))->delay(now()->addMinutes(1)); //延时分发
//            dispatch_now($user); //同步分发-已经删除
        }
        return "任务派发成功";
    }

3.执行队列任务

php artisan queue:work

horizon

用于查看队列,是一个vue写的仪表盘单页程序;提供对队列的工作负载,最近的作业,失败的作业,作业的重试,吞吐量和运行时指标以及进程计数的实时洞察。

https://segmentfault.com/a/1190000019491647

定时任务

一.使用call方法实现简单的定时任务

1.编写定时任务

文件:app\Console\Kernel.php

protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')->hourly();

    $schedule->call(function (){
       Log::info("使用call方法的定时任务,每分钟执行一次".date("Y-m-d H:i:s"));
    })->everyMinute();

}

2.手动执行定时任务(一次)

php artisan schedule:run

*注意:如果需要一直执行,在linux终端的定时任务中输入 crontab -e 然后填入

* * * * * php artisan schedule:run >> /dev/null 2>&1

2.基于 Command 的定时任务

1.创建命令

php artisan make:command TestCommend

该命令会在 app/Console/Commands 目录下生成对应的 文件

2.修改生成的文件

//app/Console/Commands/TestCommend.php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class TestCommend extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sche:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info("command命令执行的定时任务");
//        return Command::SUCCESS;
    }
}

3.crontab 添加定时任务

* * * * * php /www/wwwroot/default/laravel8/artisan sche:test >> /dev/null 2>&1
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值