Skip to content

Artisan Console

Giới thiệu (Introduction)

Artisan là giao diện dòng lệnh (CLI — Command Line Interface) đi kèm với Laravel. Artisan nằm ở gốc ứng dụng dưới dạng script artisan và cung cấp hàng loạt commands hữu ích trong quá trình phát triển.

Xem danh sách tất cả Artisan commands:

bash
php artisan list

Xem help cho command cụ thể:

bash
php artisan help migrate

Tinker (REPL)

Laravel Tinker là REPL (Read-Eval-Print Loop) mạnh mẽ cho Laravel, được cung cấp bởi package PsySH.

Cài đặt:

bash
composer require laravel/tinker

Khởi chạy:

bash
php artisan tinker

Trong Tinker, bạn có thể tương tác với toàn bộ ứng dụng — Eloquent models, jobs, events, v.v.

Viết Commands (Writing Commands)

Tạo Commands (Generating Commands)

bash
php artisan make:command SendEmails

Tạo class command mới trong app/Console/Commands.

Cấu trúc Command (Command Structure)

php
<?php

namespace App\Console\Commands;

use App\Mail\OrderShipped;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class SendEmails extends Command
{
    /**
     * Tên và signature của command.
     */
    protected $signature = 'mail:send {user}';

    /**
     * Mô tả command.
     */
    protected $description = 'Gửi email đến user';

    /**
     * Thực thi command.
     */
    public function handle(): void
    {
        Mail::to(User::find($this->argument('user')))
            ->send(new OrderShipped);
    }
}

Closure Commands

Closure-based commands là giải pháp thay thế cho class commands. Trong file routes/console.php:

php
use Illuminate\Support\Facades\Artisan;

Artisan::command('mail:send {user}', function (string $user) {
    $this->info("Đang gửi email đến: {$user}!");
})->purpose('Gửi email đến user');

Isolatable Commands

Đôi khi bạn muốn đảm bảo chỉ một instance command chạy tại một thời điểm. Implement interface Isolatable:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;

class SendEmails extends Command implements Isolatable
{
    // ...
}

Định nghĩa Input (Defining Input Expectations)

Arguments

Định nghĩa arguments trong property signature:

php
// Argument bắt buộc
protected $signature = 'mail:send {user}';

// Argument tùy chọn
protected $signature = 'mail:send {user?}';

// Argument với giá trị mặc định
protected $signature = 'mail:send {user=foo}';

Options

php
// Option không giá trị (flag)
protected $signature = 'mail:send {user} {--queue}';

// Option với giá trị
protected $signature = 'mail:send {user} {--queue=}';

// Option với giá trị mặc định
protected $signature = 'mail:send {user} {--queue=default}';

// Shortcut
protected $signature = 'mail:send {user} {--Q|queue}';

Input Arrays

php
// Array arguments
protected $signature = 'mail:send {user*}';
// php artisan mail:send 1 2

// Array options
protected $signature = 'mail:send {--id=*}';
// php artisan mail:send --id=1 --id=2

Input Descriptions

php
protected $signature = 'mail:send
    {user : ID user nhận email}
    {--queue : Có đẩy vào queue hay không}';

Command I/O

Lấy Input (Retrieving Input)

php
public function handle(): void
{
    $userId = $this->argument('user');
    $arguments = $this->arguments();

    $queueName = $this->option('queue');
    $options = $this->options();
}

Hỏi Input (Prompting for Input)

php
public function handle(): void
{
    $name = $this->ask('Tên của bạn?');
    $password = $this->secret('Mật khẩu?');

    if ($this->confirm('Bạn có muốn tiếp tục?')) {
        // ...
    }

    $name = $this->anticipate('Tên?', ['Taylor', 'Dayle']);
    $name = $this->choice('Tên?', ['Taylor', 'Dayle'], $defaultIndex);
}

Xuất Output (Writing Output)

php
public function handle(): void
{
    $this->info('Hiển thị message.');    // Xanh lá
    $this->error('Có lỗi xảy ra!');     // Đỏ
    $this->warn('Cảnh báo!');            // Vàng
    $this->line('Dòng bình thường.');    // Không màu
    $this->newLine();                    // Dòng trống
    $this->newLine(3);                   // 3 dòng trống
}

Tables (Bảng)

php
$this->table(
    ['Name', 'Email'],
    User::all(['name', 'email'])->toArray()
);

Progress Bars (Thanh tiến trình)

php
$users = App\Models\User::all();

$bar = $this->output->createProgressBar(count($users));
$bar->start();

foreach ($users as $user) {
    $this->performTask($user);
    $bar->advance();
}

$bar->finish();

Hoặc dùng withProgressBar:

php
$this->withProgressBar(User::all(), function (User $user) {
    $this->performTask($user);
});

Đăng ký Commands (Registering Commands)

Laravel tự động quét thư mục app/Console/Commands và đăng ký commands. Để đăng ký thêm thư mục:

php
// bootstrap/app.php
->withCommands([
    __DIR__.'/../app/Domain/Orders/Commands',
])

Thực thi Commands bằng Code (Programmatically Executing Commands)

php
use Illuminate\Support\Facades\Artisan;

// Gọi command
$exitCode = Artisan::call('mail:send', [
    'user' => 1, '--queue' => 'default'
]);

// Hoặc truyền string
Artisan::call('mail:send 1 --queue=default');

// Queue command chạy background
Artisan::queue('mail:send', [
    'user' => 1, '--queue' => 'default'
]);

Gọi Commands từ Commands khác

php
public function handle(): void
{
    $this->call('mail:send', ['user' => 1, '--queue' => 'default']);

    // Gọi mà không hiển thị output
    $this->callSilently('mail:send', ['user' => 1]);
}

Signal Handling

Xử lý OS signals (SIGINT khi Ctrl+C):

php
use Symfony\Component\Console\Command\SignalableCommandInterface;

class StartServer extends Command implements SignalableCommandInterface
{
    public function getSubscribedSignals(): array
    {
        return [SIGINT, SIGTERM];
    }

    public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
    {
        $this->info('Đang dọn dẹp...');
        return false;
    }
}

Stub Customization

Tùy chỉnh các file stub mà Artisan dùng khi tạo commands:

bash
php artisan stub:publish

Events

Artisan dispatch các events khi chạy commands: Illuminate\Console\Events\ArtisanStarting, CommandStarting, CommandFinished.