laravel 框架基础 学习整理
一. Laravel 數據庫遷移
php artian make:migration create_table_articles --create=articles
在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();}); }php artisan migrate
php artisan migrate:rollback
- 回滾所有應用的遷移 (危險操作) php artisan migrate:reset
- 回滾遷移并運行: php artisan migrate:refresh
? Ps:此命令先將所有的數據遷移文件進行回滾,然后重新生成遷移;也就是說先刪除所有遷移文件中的表,再生成所有遷移文件的表(所有數據將丟失)
使用遷移文件新增字段
如果要修改字段屬性,千萬不要在原來的遷移文件中對字段進行操作;
要修改一個表的字段屬性,在laravel中以新增一個遷移文件的形式進行增加和修改
修改/刪除字段
將doctrine/dbal 依賴添加到composer.json中
composer require doctrine/dbal
創建修改遷移文件
php artisan make:migration alter_users_edit_compony --table=users
php artisan migrate --path=database/migrations/2021_12_22_031201_alter_users_edit_compony.php
具體參考文章:https://www.cnblogs.com/rianley/p/9518422.html
二. laravel數據填充
執行命令后會在database/seeders目錄下生成UsersTableSeeds.php文件;
執行單個數據填充命令
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<?phpnamespace 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方法中寫具體的業務邏輯
<?phpnamespace 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.phpprotected $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.phppublic 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 <?phpnamespace 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總結
以上是生活随笔為你收集整理的laravel 框架基础 学习整理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: phpstrom 操作技巧
- 下一篇: 配置lamp+supervisor