- vừa được xem lúc

[Artisan Console] Giải thích toàn bộ Artisan Command (P1)

0 0 14

Người đăng: Đỗ Đức Thanh

Theo Viblo Asia

I. Artisan Console là gì ?

Về cơ bản Artisan là một giao diện command line được hỗ trợ bới Laravel với tập hợp một danh sách các dòng lệnh hữu ích để giúp người dùng trong quá trình build project.

Nguyên văn Laravel docs mô tả:

Artisan is the command line interface included with Laravel. Artisan exists at the root of your application as the artisan script and provides a number of helpful commands that can assist you while you build your application.

II. Đặt vấn đề một chút

Trong quá trình làm việc với Laravel thì chắc hẳn không ít anh em "động chạm" tới những câu lệnh artisan đúng không ? Vì nhiều lý do khác nhau nên các anh em có thể biết, không biết hoặc là không biết đủ về khái niệm, tác dụng và cách hoạt động của những câu artisan command đúng không nhỉ ? Ví dụ tôi đã không ít lần gặp một số anh em trong team của tôi được yêu cầu là phải lên server dev xóa cache thì các anh em đấy dùng tùm lum , từa lưa các câu lệnh artisan xóa cache như là :

php artisan cache:clear
php artisan config:cache
php artisan config:clear
php artisan optimize

Ok điều này thì không sai , người anh em này thích chạy bao nhiêu câu lệnh artisan cũng được miễn là đạt được mục đích là "xóa cache", nhưng thực ra chỉ cần chạy một câu lệnh đầu tiên là đủ, đấy là nếu anh em đó hiểu được khái niệm thực sự của từng câu lệnh artisan mà anh em đó dùng .

Bây giờ tôi lấy một ví dụ cụ thể hơn một chút nhé :

Giả sử trên môi trường product, để tối ưu hóa load view, một dev cũ đã tạo ra một bản sao view và lưu vào hệ thống cache.

Một dev mới đã thêm một config vào file môi trường (.env) và vì config đã được cache lại, buộc họ phải xóa cache config để hệ thống cập nhật đoạn config mới.

Tuy nhiên, câu lệnh mà dev này dùng là php artisan cache:clear. Vấn đề ở đây là nếu dùng lệnh này, toàn bộ các file cache được tạo ra bởi Laravel sẽ bị xóa, bao gồm cả cache của ứng dụng và các tệp cache của framework, trong đó có cả cache view. Điều này làm cho việc tối ưu hóa load view trở nên không hiệu quả.

Anh em có thấy quen không 😄 , có thấy bản thân mình trong ví dụ trên không. Thật ra anh em nào ít động chạm tới những môi trường như product/stg thì trong ví dụ trên các anh em sử dụng php artisan cache:clear thì các anh em cũng sẽ đạt được mục đích thôi . Nhưng tôi nghĩ anh em nên hiểu rõ nhưng gì mình làm , hiểu sâu những gì mình gõ thì sẽ rất tốt cho em nên tôi viết bài này nhằm mục đích giải thích "chi tiết" những artisan command mà "có thể" anh em dùng thường xuyên nhưng không hiểu hết về nó. Bắt đầu nhé!!

III. Tổng quan một chút

Tôi sẽ show trước danh sách command mà laravel 9.x hỗ trợ :

λ php artisan list
Laravel Framework 9.52.4 Usage: command [options] [arguments] Options: -h, --help Display help for the given command. When no command is given display help for the list command -q, --quiet Do not output any message -V, --version Display this application version --ansi|--no-ansi Force (or disable --no-ansi) 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: about Display basic information about your application clear-compiled Remove the compiled class file completion Dump the shell completion script db Start a new database CLI session docs Access the Laravel documentation down Put the application into maintenance / demo mode env Display the current framework environment help Display help for a command inspire Display an inspiring quote list List commands migrate Run the database migrations optimize Cache the framework bootstrap files serve Serve the application on the PHP development server test Run the application tests tinker Interact with your application up Bring the application out of maintenance mode 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 config config:cache Create a cache file for faster configuration loading config:clear Remove the configuration cache file db db:monitor Monitor the number of connections on the specified database db:seed Seed the database with records db:show Display information about the given database db:table Display information about the given database table db:wipe Drop all tables, views, and types env env:decrypt Decrypt an environment file env:encrypt Encrypt an environment file event event:cache Discover and cache the application's events and listeners event:clear Clear all cached events and listeners event:generate Generate the missing events and listeners based on registration event:list List the application's events and listeners key key:generate Set the application key make make:cast Create a new custom Eloquent cast class make:channel Create a new channel class make:command Create a new Artisan command make:component Create a new view component class 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:scope Create a new scope class 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 model model:prune Prune models that are no longer needed model:show Show information about an Eloquent model notifications notifications:table Create a migration for the notifications table optimize optimize:clear Remove the cached bootstrap files package package:discover Rebuild the cached package manifest queue queue:batches-table Create a migration for the batches database table queue:clear Delete all of the jobs from the specified 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:monitor Monitor the size of the specified queues queue:prune-batches Prune stale entries from the batches database queue:prune-failed Prune stale entries from the failed jobs table queue:restart Restart queue worker daemons after their current job queue:retry Retry a failed queue job queue:retry-batch Retry the failed jobs for a batch 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 sail sail:add Add a service to an existing Sail installation sail:install Install Laravel Sail's default Docker Compose file sail:publish Publish the Laravel Sail Docker files sanctum sanctum:prune-expired Prune tokens expired for more than specified number of hours. schedule schedule:clear-cache Delete the cached mutex files created by scheduler schedule:list List all scheduled tasks schedule:run Run the scheduled commands schedule:test Run a scheduled command schedule:work Start the schedule worker schema schema:dump Dump the given database schema session session:table Create a migration for the session database table storage storage:link Create the symbolic links configured for the application stub stub:publish Publish all stubs that are available for customization 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

Ngoài ra mỗi câu lệnh đều có kèm theo tham số , để hiển thi và mô tả những đối số và tùy chọn có thể sử dụng, ta sử dụng câu lệnh php artisan help migrate

λ 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(s) to the migrations files to be executed (multiple values allowed) --realpath Indicate any provided migration file paths are pre-resolved absolute paths --schema-path[=SCHEMA-PATH] The path to a schema dump file --pretend Dump the SQL queries that would be run --seed Indicates if the seed task should be re-run --seeder[=SEEDER] The class name of the root seeder --step Force the migrations to be run so they can be rolled back individually --isolated[=ISOLATED] Do not run the command if another instance of the command is already running [default: false] -h, --help Display help for the given command. When no command is given display help for the list command -q, --quiet Do not output any message -V, --version Display this application version --ansi|--no-ansi Force (or disable --no-ansi) 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

IV. Chi tiết commands

1. php artisan about

Lệnh này hiển thị thông tin cơ bản về ứng dụng của bạn

 php artisan about Environment ...................................................................................................................................... Application Name ......................................................................................................................... Laravel Laravel Version ........................................................................................................................... 9.52.4 PHP Version ............................................................................................................................... 8.1.10 Composer Version ........................................................................................................................... 2.4.1 Environment ................................................................................................................................ local Debug Mode ............................................................................................................................... ENABLED URL .................................................................................................................................... localhost Maintenance Mode ............................................................................................................................. OFF Cache ............................................................................................................................................ Config ................................................................................................................................ NOT CACHED Events ................................................................................................................................ NOT CACHED Routes ................................................................................................................................ NOT CACHED Views ..................................................................................................................................... CACHED Drivers .......................................................................................................................................... Broadcasting .............................................................................................................................. pusher Cache ....................................................................................................................................... file Database ................................................................................................................................... pgsql Logs .............................................................................................................................. stack / single Mail ........................................................................................................................................ smtp Queue ....................................................................................................................................... sync Session ..................................................................................................................................... file

2. php artisan clear-compiled

Lệnh này được sử dụng để xóa bỏ file compiled.php trong thư mục bootstrap/cache của ứng dụng Laravel. File compiled.php là một file được tạo ra bởi Laravel để tối ưu hóa hiệu suất của ứng dụng. File này chứa một số tập lệnh PHP đã được biên dịch trước đó, giúp cho các tập lệnh này có thể được thực thi nhanh hơn.

3. php artisan completion

Lệnh này trong Laravel Framework được sử dụng để tạo ra các tùy chọn cho các câu lệnh Artisan có sẵn. Nó giúp cho việc sử dụng các câu lệnh Artisan trở nên dễ dàng hơn bằng cách cung cấp các gợi ý về cú pháp và tùy chọn cho người dùng khi nhập các lệnh Artisan.

Khi bạn chạy lệnh php artisan completion, Laravel sẽ tạo ra một file script shell có tên artisan trong thư mục hiện tại của bạn. File này chứa các định nghĩa cho các tùy chọn của các câu lệnh Artisan và được sử dụng để cung cấp các gợi ý và đề xuất khi người dùng sử dụng câu lệnh Artisan.

Sau khi chạy lệnh php artisan completion, bạn cần phải kích hoạt tính năng tự động hoàn thành trong command-line interface của bạn. Cách kích hoạt tính năng tự động hoàn thành có thể khác nhau tùy thuộc vào command-line interface mà bạn đang sử dụng, nhưng thường là sử dụng lệnh source để đọc và thực thi file script shell artisan được tạo ra.

Ví dụ, nếu bạn đang sử dụng bash shell trên Linux, bạn có thể kích hoạt tính năng tự động hoàn thành bằng cách thêm dòng sau vào tệp cấu hình ~/.bashrc:

source path/to/artisan

Sau khi kích hoạt tính năng tự động hoàn thành, khi bạn nhập các lệnh Artisan, các gợi ý về cú pháp và tùy chọn sẽ được hiển thị để giúp cho việc sử dụng các câu lệnh Artisan trở nên dễ dàng hơn.

4. Các lệnh php artisan chứa từ khóa db

Laravel Framework cung cấp một số lệnh Artisan để quản lý cơ sở dữ liệu. Tất cả các lệnh Artisan liên quan đến cơ sở dữ liệu đều bắt đầu với tiền tố db. Một vài ví dụ cho a/e dễ hình dung:

  1. php artisan db:seed: Được sử dụng để chạy các file Seeder để tạo dữ liệu mẫu cho cơ sở dữ liệu.

  2. php artisan db:wipe: Được sử dụng để xóa toàn bộ dữ liệu của cơ sở dữ liệu và chạy lại tất cả các tập lệnh Migration.

  3. php artisan db:rollback: Được sử dụng để rollback (hoàn tác) lệnh Migration cuối cùng đã được chạy trên cơ sở dữ liệu.

  4. php artisan db:seed --class=ClassName: Được sử dụng để chạy Seeder chỉ định theo tên lớp của Seeder.

  5. php artisan db:seed --database=connection_name: Được sử dụng để chạy Seeder trên một kết nối cơ sở dữ liệu cụ thể.

  6. php artisan db:seed --force: Được sử dụng để chạy Seeder mà không cần xác nhận từ người dùng.

  7. php artisan db:table: Được sử dụng để tạo Migration mới cho bảng cơ sở dữ liệu.

  8. php artisan db:drop: Được sử dụng để xóa toàn bộ cơ sở dữ liệu.

  9. php artisan db:create: Được sử dụng để tạo một cơ sở dữ liệu mới.

5. php artisan docs

Lệnh này sẽ access tới laravel documentation.

6. Cặp php artisan down/up

Chỉ đơn giản là bật tắt chế độ maintenance của application.

7. php artisan env

Check môi trường tại thời điểm chạy lệnh này

8. php artisan inspire

Kiểu code nản quá thì các bạn gõ lệnh này 😄 , lệnh này chỉ hiển thị thông điệp lấy lại cảm hứng cho ae và tất nhiên ae cần một chút tiếng anh để đọc hiểu nó 😃.

9. php artisan optimize

Sau khi hoàn thành project thì Laravel có hỗ trợ câu lệnh nào tối ưu hiệu suất application không ? Câu trả lời là có và đây là một câu như vậy, về cơ bản khi chạy câu lệnh này Laravel sẽ thực hiện một số nhiệm vụ tối ưu hóa bao gồm:

  1. Biên dịch các file Blade templates thành các file PHP được lưu trữ trong thư mục cache để giảm thời gian tải trang.
  2. Tạo các file cache để tăng tốc độ tải các file cấu hình và file phiên bản.
  3. Tạo ra một file tối ưu hóa được lưu trữ trong thư mục cache để giảm thời gian tải ứng dụng.
  4. Xóa tất cả các file tạm thời và cache không cần thiết.

Quá tuyệt với, nhưng tốt nhất câu này nên chạy khi ae đã release product xong và chuẩn bị triển khai nhé ^^

10. php artisan tinker

Lệnh này khá hay nhưng ít được ae để ý, về cơ bản thì lệnh này được sử dụng để khởi chạy môi trường tương tác với ứng dụng Laravel. Nó cho phép bạn tương tác với ứng dụng Laravel của mình thông qua một command-line interface (CLI) để thực hiện các thao tác cơ bản như tìm kiếm, truy vấn, tạo và sửa đổi dữ liệu trong cơ sở dữ liệu, kiểm tra các hàm và lớp của ứng dụng, v.v.

Khi bạn chạy lệnh php artisan tinker, Laravel sẽ khởi tạo môi trường tương tác và hiển thị dấu nhắc lệnh Psy Shell. Từ đó, bạn có thể sử dụng các lệnh tương tác với ứng dụng Laravel của mình như sau:

  • Sử dụng các lớp và đối tượng Laravel
  • Gọi các hàm và phương thức trong Laravel
  • Truy vấn cơ sở dữ liệu và thao tác với dữ liệu

Ví dụ, bạn có thể sử dụng lệnh DB::table('users')->get() để lấy danh sách tất cả các người dùng từ bảng users trong cơ sở dữ liệu.

Lệnh php artisan tinker là một công cụ hữu ích để phát triển và kiểm tra ứng dụng Laravel của bạn một cách nhanh chóng và hiệu quả.

11. php artisan serve

Lệnh này sẽ khởi động ứng dụng trên máy chủ phát triển PHP.

12. Các lệnh php artisan chứa từ khóa migrate

Lệnh này chắc đã quá quen thuộc với anh em mình rồi , tôi chỉ giải thích ngắn gọn là lệnh này sẽ làm việc với các file migration trong ứng dụng Laravel. Dưới đây là chi tiết các command ae tham khảo:

  1. php artisan migrate - chạy tất cả các file migration mới nhất chưa được chạy trên cơ sở dữ liệu.
  2. php artisan migrate:rollback - hủy bỏ migration mới nhất đã chạy trên cơ sở dữ liệu.
  3. php artisan migrate:reset - hủy bỏ tất cả các migration đã chạy trên cơ sở dữ liệu và trở về trạng thái ban đầu.
  4. php artisan migrate:fresh - xoá toàn bộ các bảng trong cơ sở dữ liệu và chạy lại toàn bộ các file migration.
  5. php artisan migrate:status - hiển thị trạng thái của tất cả các migration đã chạy trên cơ sở dữ liệu.
  6. php artisan migrate:install - tạo bảng migration trong cơ sở dữ liệu để theo dõi trạng thái của các file migration.
  7. php artisan migrate:make - tạo một file migration mới.
  8. php artisan migrate:refresh - thực hiện kết hợp giữa rollback và fresh, nghĩa là xoá toàn bộ các bảng và chạy lại tất cả các file migration.

Còn tiếp ...

Bài viết được tham khảo:

https://laravel.com/docs/9.x/artisan

Bình luận

Bài viết tương tự

- vừa được xem lúc

Tìm hiểu về Livewire trong Laravel

Giới Thiệu. Livewire là một full-stack framework cho Laravel giúp việc xây dựng các giao diện động trở nên đơn giản hơn.

0 1 218

- vừa được xem lúc

Tải cả thư viện sách lên website chỉ trong 1 nốt nhạc với Laravel!

Giới thiệu bài toán:. Sau nhiều giờ ngồi upload từng cuốn e-book lên website - 1 việc cần thiết nhưng thật sự tốn thời gian.

0 0 29

- vừa được xem lúc

DataTable và Laravel

1. Giới thiệu:.

0 0 83

- vừa được xem lúc

Hướng dẫn làm chức năng đăng ký tài khoảng bằng cách xác thực email với mã OTP giống như Facebook bằng Laravel 8x

Xin chào tất cả mọi người, mình sẽ hướng dẫn mọi người làm chức năng gửi gmail xác thực người dùng bằng mã OTP giống như Facebook bằng Laravel 8x.Bài viết này dành cho người đã từng học qua Laravel cơ

0 0 33

- vừa được xem lúc

Câu chuyện về caching trong laravel

Caching là gì, tại sao phải caching. Laravel có thể caching những gì.

0 0 53

- vừa được xem lúc

Tìm hiểu về Service Container trong Laravel

I - Service Container là gì . liên kết những thứ chúng ta cần để ứng dụng Laravel một cách trơn chu.

0 0 27