Laravel Artisan Là Gì?

Laravel Artisan Là Gì?
Laravel Artisan là giao diện command-line. Nó chính là một công cụ được thêm vào Laravel để hỗ trợ các bạn xây dựng các ứng dụng.

Khi lần đầu tiên tiếp cận với framework Laravel, các bạn sẽ ngạc nhiên khi Laravel có một công cụ dòng lệnh Artisan. Khi đề cập đến các công cụ dòng lệnh, thì các bạn có thấy nó khó không? Có khó hiểu không? Trên thực tế, Laravel Artisan cũng không có gì khó hiểu lắm đâu. Chúng ta hãy cùng nhau tìm hiểu về nó. 

 

Giới thiệu về Laravel Artisan 

 

Artisan là giao diện command-line và thường được thêm vào Laravel. Nó cung cấp một số lệnh hỗ trợ các bạn khi xây dựng các ứng dụng. Đồng thời, nó cũng giúp các bạn giảm thời gian viết code và tự động hóa một số công việc khác. Các bạn sử dụng câu lệnh php artisan list để kiểm danh sách các câu lệnh hỗ trợ từ Artisan. 

 

blog git:(master) ✗ php artisan list

Laravel Framework 5.6.26

Usage:

  command [options] [arguments]

Options:

  -h, --help            Display this help message

  -q, --quiet           Do not output any message

  -V, --version         Display this application version

      --ansi            Force ANSI output

      --no-ansi         Disable ANSI output

  -n, --no-interaction  Do not ask any interactive question

      --env[=ENV]       The environment the command should run under

  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:

  clear-compiled       Remove the compiled class file

  down                 Put the application into maintenance mode

  env                  Display the current framework environment

  help                 Displays help for a command

  inspire              Display an inspiring quote

  list                 Lists commands

  migrate              Run the database migrations

  preset               Swap the front-end scaffolding for the application

  serve                Serve the application on the PHP development server

  tinker               Interact with your application

  up                   Bring the application out of maintenance mode

 app

  app:name             Set the application namespace

 auth

  auth:clear-resets    Flush expired password reset tokens

 cache

  cache:clear          Flush the application cache

  cache:forget         Remove an item from the cache

  cache:table          Create a migration for the cache database table

 command

  command:name         Command description

 config

  config:cache         Create a cache file for faster configuration loading

  config:clear         Remove the configuration cache file

 db

  db:seed              Seed the database with records

 event

  event:generate       Generate the missing events and listeners based on registration

 key

  key:generate         Set the application key

 make

  make:auth            Scaffold basic login and registration views and routes

  make:channel         Create a new channel class

  make:command         Create a new Artisan command

  make:controller      Create a new controller class

  make:event           Create a new event class

  make:exception       Create a new custom exception class

  make:factory         Create a new model factory

  make:job             Create a new job class

  make:listener        Create a new event listener class

  make:mail            Create a new email class

  make:middleware      Create a new middleware class

  make:migration       Create a new migration file

  make:model           Create a new Eloquent model class

  make:notification    Create a new notification class

  make:observer        Create a new observer class

  make:policy          Create a new policy class

  make:provider        Create a new service provider class

  make:request         Create a new form request class

  make:resource        Create a new resource

  make:rule            Create a new validation rule

  make:seeder          Create a new seeder class

  make:test            Create a new test class

 migrate

  migrate:fresh        Drop all tables and re-run all migrations

  migrate:install      Create the migration repository

  migrate:refresh      Reset and re-run all migrations

  migrate:reset        Rollback all database migrations

  migrate:rollback     Rollback the last database migration

  migrate:status       Show the status of each migration

 notifications

  notifications:table  Create a migration for the notifications table

 package

  package:discover     Rebuild the cached package manifest

 queue

  queue:failed         List all of the failed queue jobs

  queue:failed-table   Create a migration for the failed queue jobs database table

  queue:flush          Flush all of the failed queue jobs

  queue:forget         Delete a failed queue job

  queue:listen         Listen to a given queue

  queue:restart        Restart queue worker daemons after their current job

  queue:retry          Retry a failed queue job

  queue:table          Create a migration for the queue jobs database table

  queue:work           Start processing jobs on the queue as a daemon

 route

  route:cache          Create a route cache file for faster route registration

  route:clear          Remove the route cache file

  route:list           List all registered routes

 schedule

  schedule:run         Run the scheduled commands

 session

  session:table        Create a migration for the session database table

 storage

  storage:link         Create a symbolic link from "public/storage" to "storage/app/public"

 vendor

  vendor:publish       Publish any publishable assets from vendor packages

 view

  view:cache           Compile all of the application's Blade templates

  view:clear           Clear all compiled view files

 

Sau khi đã nhập tất cả dòng lệnh ở trên vào command-line, các bạn sẽ thấy nó hiện ra một danh sách các hỗ trợ của artisan. Mỗi dòng lệnh thường có kèm theo tham số dùng để hiển thị và mô tả đầy đủ các đối số. Các bạn có thể sử dụng tùy chọn và thậm chí là sử dụng câu lệnh php artisan help migrate. 

 

➜  blog git:(master) ✗ php artisan help migrate

Description:

  Run the database migrations

Usage:

  migrate [options]

Options:

      --database[=DATABASE]  The database connection to use.

      --force                Force the operation to run when in production.

      --path[=PATH]          The path to the migrations files to be executed.

      --realpath             Indicate any provided migration file paths are pre-resolved absolute paths.

      --pretend              Dump the SQL queries that would be run.

      --seed                 Indicates if the seed task should be re-run.

      --step                 Force the migrations to be run so they can be rolled back individually.

  -h, --help                 Display this help message

  -q, --quiet                Do not output any message

  -V, --version              Display this application version

      --ansi                 Force ANSI output

      --no-ansi              Disable ANSI output

  -n, --no-interaction       Do not ask any interactive question

      --env[=ENV]            The environment the command should run under

  -v|vv|vvv, --verbose       Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

 

Laravel REPL là gì? 

 

REPL là viết tắt của Read, Eval và Print Loop. REPL còn có tên gọi là language shell. Nó là ngôn ngữ cho phép chúng ta lặp đi lặp lại các thao tác đọc dữ liệu, tính toán dữ liệu và in ra màn hình. Các ứng dụng Laravel (trong đó có Tinker) là ngôn ngữ REPL được hỗ trợ bởi PsySH.

 

>php artisan tinker

Psy Shell v0.8.3 (PHP 5.6.20 ΓÇö cli) by Justin Hileman

New version is available (current: v0.8.3, latest: v0.8.8)

>>>

 

Câu lệnh tạo ra Laravel Artisan

 

Ngoài các lệnh được cung cấp với Artisan, các bạn cũng có thể tạo một số câu lệnh linh động của riêng mình. Các lệnh như vậy thường được lưu trữ trong thư mục app/Console/Commands. Tuy nhiên, các bạn có quyền tự chọn vị trí lưu giữ của riêng các bạn. Miễn sao là lệnh đó phải đảm bảo Composer có thể tải được. 

 

Để tạo một lệnh mới, các bạn nên sử dụng dòng lệnh make: lệnh Artisan. Vì lệnh này sẽ tự động tạo một lớp lệnh mới trong thư mục app/Console/Commands. Nếu thấy thư mục này không tồn tại trong ứng dụng của bạn, thì cũng đừng quá lo. Vì nó cũng sẽ được tạo ra lần đầu tiên khi bạn cho chạy dòng lệnh make: command Artisan. Lệnh sau khi đã được tạo sẽ gồm có tập hợp các thuộc tính và phương thức mặc định có mặt trên tất cả các lệnh. 

 

php artisan make:command SendEmails

 

Khi đã tạo lệnh, các bạn nên thêm vào các đặc tính signature và description của lớp đó. Nó sẽ được sử dụng khi hiển thị câu lệnh của bạn trên màn hình danh sách. Đồng thời, phương thức xử lý cũng sẽ được gọi khi lệnh của bạn đã được thực hiện. Bạn cũng có thể đặt logic lệnh trong phương thức này. Để tái sử dụng mã nhiều lần, thực hành liên tục là cách giữ cho các lệnh giao diện điều khiển của bạn sáng và trì hoãn các dịch vụ ứng dụng để hoàn thành nhiệm vụ. Xem ví dụ bên dưới:

 

namespace App\Console\Commands;

use App\User;

use App\DripEmailer;

use Illuminate\Console\Command;

class SendEmails extends Command

{

    /**

     * The name and signature of the console command.

     *

     * @var  string

     */

    protected $signature = 'email:send {user}';

    /**

     * The console command description.

     *

     * @var  string

     */

    protected $description = 'Send drip e-mails to a user';

    /**

     * The drip e-mail service.

     *

     * @var  DripEmailer

     */

    protected $drip;

    /**

     * Create a new command instance.

     *

     * @param    DripEmailer  $drip

     * @return  void

     */

    public function __construct(DripEmailer $drip)

    {

        parent::__construct();

        $this->drip = $drip;

    }

    /**

     * Execute the console command.

     *

     * @return  mixed

     */

    public function handle()

    {

        $this->drip->send(User::find($this->argument('user')));

    }

}

 

Khi đã đăng ký xong, bạn sẽ thấy nó xuất hiện thông tin câu lệnh user:create khi liệt kê các lệnh artisan (php artisan list). Nó cũng có thể thực hiện luôn lệnh php artisan user:create như các lệnh artisan sẵn có trước đó. 

 

Các tham số câu lệnh Artisan 

 

/**

 * The name and signature of the console command.

 *

 * @var  string

 */

protected $signature = 'user:create {userType} {numberOfUser=1}';

 

Nếu bạn muốn tạo 20 người dùng có quyền quản trị, thì bạn nên thực hiện lệnh php artisan user:create admin 20. Các tùy chọn trong câu lệnh Artisan cũng được định nghĩa trong $signature, nghĩa là nó cũng sẽ được đưa vào trong hai dấu ngoặc nhọn với tiền tố là -. Ví dụ {–options} có 2 loại tùy chọn: loại nhận giá trị và loại không nhận giá trị.

 

/**

 * The name and signature of the console command.

 *

 * @var  string

 */

protected $signature = 'user:create {userType} {numberOfUser} {--queue}';

 

Ở ví dụ trên, queue được xác định khi bạn thực hiện câu lệnh artisan. Khi đó, giá trị tùy chọn này sẽ là true. Ngược lại, nếu bạn không truyền queue thì giá trị trong tùy chọn đó sẽ là false. Ví dụ câu lệnh php artisan user:create admin 20 thì queue sẽ là tạo ra 20 quản trị viên bằng cách đưa việc này vào trong hàng đợi của hệ thống. Với các tùy chọn, các bạn cũng có thể thu ngắn gọn hơn {–Q|queue}. Khi đó, bạn có thể thay queue trong câu lệnh artisan thành –Q. Điều này tương tự khi các bạn kiểm tra phiên bản của Laravel Artisan. 

 

php artisan --version Laravel Framework 5.4.23

php artisan -V Laravel Framework 5.4.23

 

Bạn có thể đưa vào câu lệnh dưới dạng mảng từ các tham số và tùy chọn ở ví dụ trên. Khi đó, bạn nên sử dụng ký tự * để ngụ ý các đầu vào là dạng mảng. 

 

/**

 * The name and signature of the console command.

 *

 * @var  string

 */

protected $signature = 'user:delete {user*}';

 

Khi thực hiện lệnh php artisan user:delete 1 2 3 thì tham số user sẽ là một mảng số [1, 2, 3]. Tương tự cho tùy chọn, bạn thực hiện

 

/**

 * The name and signature of the console command.

 *

 * @var  string

 */

protected $signature = 'user:delete {--id=*}';

 

Dòng lệnh artisan sẽ như sau: php artisan user:delete –id = 1 –id=2.  Với thuộc tính signature, bạn cũng có thể đưa vào các text mô tả cho từng tham số hoặc tùy chọn khi liệt kê danh sách các lệnh artisan. Có như vậy, bạn sẽ biết được các tham số và tùy chọn đó để làm gì.

 

/**

 * The name and signature of the console command.

 *

 * @var  string

 */

protected $signature = 'user:create 

                       {userType : Type of user example admin, user...} 

                       {numberOfUser=1 : Number of user will create, default one user created} {--queue}';

 

Closure Commands là gì?

 

Closure commands cung cấp các định nghĩa khác của console commands như classes. Tương tự route Closures (thay thế cho các controllers), hàm commands của file app/Console/Kernel.php, Laravel có thể load file routes/console.php. 

 

/**

 * Register the Closure based commands for the application.

 *

 * @return    void

 */

protected function commands()

{

    require base_path('routes/console.php');

}

 

Dù file này không thực sự được định nghĩa HTTP routes, nó cũng sẽ định nghĩa console based entry points (routes) vào một ứng dụng. Ở trong file này, các bạn có thể định nghĩa tất cả closure based routes sử dụng hàm Artisan::command. Hàm command thường chấp nhận 2 tham số - command signature và closure nhận tham số (tùy chọn). 

 

Artisan::command('post:create {active=0} {numberOfPost=1} {--queue}', function ($active, $numberOfPost) {

    $this->info('Create post successfully');

});

 

Ngoài ra, command Closures có thể type-hint thêm các dependencies mà bạn muốn để giải quyết chúng ra khỏi service container (có thể là nhận tham số command và options). 

 

use DB;

use Faker;

Artisan::command('post:create {active=0} {numberOfPost=1}', function ($active, $numberOfPost) {

    $faker = Faker\Factory::create();

    try {

        for ($i = 0; $i < $numberOfPost; $i++) {

            DB::table('posts')->insert([

                'title' => $faker->name,

                'content' => $faker->text($maxNbChars = 500);

            ]);

        }

        $thís->info($numberOfPost . ' create successfully');

    } catch (Exception $e) {

        $this->error('Error' . $e . 'when create post');

    }

});

 

Cách mô tả Closure Command 

 

Khi chúng ta định nghĩa một close based command, các bạn có thể sử dụng hàm describe để gia tăng nhiều mô tả cho command. Các mô tả như vậy sẽ thể hiện rõ ràng khi bạn bắt đầu chạy lệnh php artisan list hoặc php artisan help. 

 

use DB;

use Faker;

Artisan::command('post:create {active=0} {numberOfPost=1}', function ($active, $numberOfPost) {

    $faker = Faker\Factory::create();

    try {

        for ($i = 0; $i < $numberOfPost; $i++) {

            DB::table('posts')->insert([

                'title' => $faker->name,

                'content' => $faker->text($maxNbChars = 500);

            ]);

        }

        $thís->info($numberOfPost . ' create successfully');

    } catch (Exception $e) {

        $this->error('Error' . $e . 'when create post');

    }

})->describe('Create new post');

 

Cách đăng ký câu lệnh với hệ thống 

 

Đầu tiên, bạn cần định nghĩa rõ ràng các câu lệnh artisan. Tiếp theo, bạn đăng ký câu lệnh với hệ thống bằng cách đưa nó vào thuộc tính commands trong lớp Kernel (app/Console/Kernel.php).

 

protected $commands = [

    Commands\UserCommand::class

];

 

Sau khi bạn đã đăng ký, thông tin câu lệnh user:create sẽ hiện ra và nó cũng sẽ liệt kê các lệnh artisan (php artisan list). Hơn nữa, bạn cũng có thể thực hiện lệnh php artisan user:create tương tự như với các lệnh artisan đã có sẵn trước đó. 

 

Cách chạy câu lệnh Artisan trong chương trình 

 

Các câu lệnh Artisan trong một chương trình có thể được thực hiện trong mã chương trình khi mà chúng ta tiến hành phương thức call với façade Artisan. Bạn chú ý ở phần bật chế độ bảo trì website bằng ứng dụng. 

 

Route::get('turn-on-maintanence-mode', function(){

    Artisan::call('down');

});

 

Nếu muốn thực hiện các câu lệnh đó trong hàng chờ của hệ thống, thì bạn nên sử dụng phương thức queue.

 

Route::get('/foo', function () {

    Artisan::queue('email:send', [

        'user' => 1, '--queue' => 'default'

    ]);



    //

});

 

Ngoài ra, bạn cũng có thể truyền giá trị cho các tham số và tùy chọn của nó khi thực thi câu lệnh dưới đây: 

 

$exitCode = Artisan::call('user:create', [

    'userType' => 'admin',

    'numberOfUser' => 10

]);

Hồ Hữu Hiền

Mình là developer nên đôi khi viết bài không hay lắm mong các bạn thông cảm. Nếu muốn biết thêm thông tin về mình thì vui lòng vào website này để biết. https://huuhienqt.dev/

Bình luận (0)