Học Laravel – Bài 25: Artisan Console

Mỗi lệnh artisan đều có “help” để hiển thị các tham số và tùy chọn:

php artisan help migrate

Viết lệnh:

Bạn có thể tự build custom command trong thư mục app/Console/Commands.

Tạo 1 command: sử dụng make:command, lệnh này tạo 1 class trong thư mục trên. Ví dụ:

php artisan make:command SendEmails

Cấu trúc command:

Bạn cần định nghĩa giá trị phù hợp cho signaturedescription của class. Method handle sẽ được gọi khi command được thực thi.

Ví dụ:

<?php
 
namespace App\Console\Commands;
 
use App\Models\User;
use App\Support\DripEmailer;
use Illuminate\Console\Command;
 
class SendEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mail:send {user}';
 
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send a marketing email to a user';
 
    /**
     * Execute the console command.
     */
    public function handle(DripEmailer $drip): void
    {
        $drip->send(User::find($this->argument('user')));
    }
}

Closure command:

Cung cấp 1 cách khác để define console command như class. Trong file Kernel.php, method commands:

/**
 * Register the closure based commands for the application.
 */
protected function commands(): void
{
    require base_path('routes/console.php');
}

Trong file này bạn có thể define tất cả command sử dụng method Artisan::command:

Artisan::command('mail:send {user}', function (string $user) {
    $this->info("Sending email to: {$user}!");
});

Mô tả cho command sử dụng method purpose:

Artisan::command('mail:send {user}', function (string $user) {
    // ...
})->purpose('Send a marketing email to a user');

Tham số:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'mail:send {user}';

Tham số tùy chọn: 'mail:send {user?}'

Tham số có giá trị mặc định: 'mail:send {user=foo}'

Tùy chọn:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'mail:send {user} {--queue}';

Lệnh Artisan tương ứng: php artisan mail:send 1 --queue

Tùy chọn với giá trị:

/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'mail:send {user} {--queue=}';

Lệnh artisan: php artisan mail:send 1 --queue=default

Bạn có thể gán giá trị mặc định bằng cách thêm vào sau tên option:

'mail:send {user} {--queue=default}'

Lập trình thực thi lệnh:

Thi thoảng bạn cần thực thi lệnh ở ngoài CLI, ví dụ trong route hoặc controller. Sử dụng method call trong facade Artisan:

use Illuminate\Support\Facades\Artisan;
 
Route::post('/user/{user}/mail', function (string $user) {
    $exitCode = Artisan::call('mail:send', [
        'user' => $user, '--queue' => 'default'
    ]);
 
    // ...
});

Cách khác:

Artisan::call('mail:send 1 --queue=default');

Hàng đợi command:

Sử dụng method queue để lệnh thực thi dưới background. Trước khi sử dụng method này, đảm bảo đã cấu hình queue và đang chạy 1 queue listener:

use Illuminate\Support\Facades\Artisan;
 
Route::post('/user/{user}/mail', function (string $user) {
    Artisan::queue('mail:send', [
        'user' => $user, '--queue' => 'default'
    ]);
 
    // ...
});

Sử dụng method onConnectiononQueue để chỉ định connection hoặc queue mà Artisan command gửi đến:

Artisan::queue('mail:send', [
    'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');

Xử lý tín hiệu:

Hệ thống cho phép tín hiệu được gửi đến tiến trình đang chạy. Ví dụ tín hiệu SIGTERM là cách hệ thống hỏi 1 chương trình để terminate. Nếu bạn muốn lắng nghe tín hiệu trong Artisan console command và thực thi code khi nó xảy ra, sử dụng trap method:

/**
 * Execute the console command.
 */
public function handle(): void
{
    $this->trap(SIGTERM, fn () => $this->shouldKeepRunning = false);
 
    while ($this->shouldKeepRunning) {
        // ...
    }
}

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *