Tự Động Hóa Tạo Nội Dung với Custom Artisan Command

· 3 min read

Trong CMS file-based (như blog này), việc tạo bài viết mới thường bao gồm:

  1. Kiểm tra ngày tháng.
  2. Tạo file mới với định dạng YYYY-MM-DD-slug.md.
  3. Copy-paste header YAML frontmatter.
  4. Điền title và date.

Điều này nhàm chán và dễ sai sót. Hãy tự động hóa nó.

Mục Tiêu

Chúng ta muốn chạy:

php artisan make:post "Mastering Custom Artisan Commands"

Và có file được tạo tại content/posts/2026/02/12-mastering-custom-artisan-commands.md với header đã được điền sẵn.

Bước 1: Tạo Command

Chạy generator tiêu chuẩn:

php artisan make:command MakePostCommand

Bước 2: Định Nghĩa Signature

Mở app/Console/Commands/MakePostCommand.php.

protected $signature = 'make:post 
                        {title : Tiêu đề bài blog} 
                        {--d|draft : Tạo dưới dạng draft}';

protected $description = 'Tạo bài blog markdown mới với frontmatter';

Bước 3: Implement Logic

Chúng ta cần sử dụng Str::slug để bảo vệ filename và File facade để viết nội dung.

public function handle()
{
    $title = $this->argument('title');
    $slug = Str::slug($title);
    $date = now();
    
    // Cấu trúc: YYYY/MM/DD-slug.md
    $path = "content/posts/{$date->format('Y')}/{$date->format('m')}";
    $filename = "{$date->format('d')}-{$slug}.md";
    $fullPath = base_path("{$path}/{$filename}");

    // Đảm bảo thư mục tồn tại
    if (!File::isDirectory(base_path($path))) {
        File::makeDirectory(base_path($path), 0755, true);
    }

    if (File::exists($fullPath)) {
        $this->error("Bài viết đã tồn tại: {$filename}");
        return;
    }

    // Tạo Nội Dung
    $content = $this->getStub($title, $date, $this->option('draft'));
    
    File::put($fullPath, $content);

    $this->info("Bài blog đã được tạo thành công!");
    $this->line($fullPath);
}

Bước 4: Stub Hợp Lệ

Method getStub đơn giản trả về string template.

private function getStub($title, $date, $isDraft)
{
    $draft = $isDraft ? 'true' : 'false';
    $dateStr = $date->format('Y-m-d');

return <<<EOT
---
title: "{$title}"
date: {$dateStr}
description: ""
tags: []
draft: {$draft}
---

Viết nội dung của bạn ở đây...
EOT;
}

Bonus: Đăng Ký trong Git

Bạn thậm chí có thể tự động chạy git add trên file mới bằng cách sử dụng Process facade!

use Illuminate\Support\Facades\Process;

// ... bên trong handle
Process::run(['git', 'add', $fullPath]);
$this->info("Đã thêm vào git.");

Kết Luận

Công cụ tạo nên developer. Bằng cách dành 10 phút viết command này, bạn loại bỏ ma sát khỏi quá trình viết. Càng dễ bắt đầu viết, bạn càng có khả năng blog.

Bình luận