1. 简介

Artisan 是 Laravel 自带的命令行接口,它提供了许多实用的命令来帮助你构建 Laravel 应用

查看所有可用命令列表

  1. php artisan list
  1. Available commands:
  2. clear-compiled # optimize操作的反向,清除生成的文件
  3. down # 将站点设为维护状态
  4. env # 显示项目现在运行所处的环境(local或其他)
  5. help # 帮助信息
  6. inspire # 输出一句名言,位于routes/console.php
  7. list # 列出所有命令
  8. migrate # 运行迁移文件
  9. optimize # 优化应用程序性能,生成自动加载文件,先要运行config:cache命令
  10. preset Swap the front-end scaffolding for the application
  11. serve # 使用 PHP 内置的开发服务器启动应用 【要求 PHP 版本在 5.4 或以上】
  12. tinker # 进入与当前应用环境绑定的 REPL 环境,相当于 Rails 框架的 rails console 命令
  13. up # 将站点设回可访问状态
  14. app
  15. app:name # 设置应用程序命名空间
  16. auth
  17. auth:clear-resets # 清除过期的密码重置密钥
  18. cache
  19. cache:clear # 清除应用程序缓存
  20. cache:forget Remove an item from the cache
  21. cache:table # 创建一个缓存数据库表的迁移
  22. config
  23. config:cache # 生成文件 bootstrap/cache/config.php,把 config 文件夹里所有配置信息合并到一个文件里,减少运行时文件的载入数量,不会自动重载,开发时候建议关闭
  24. config:clear # 清除缓存的config.php文件
  25. db
  26. db:seed # 生成测试数据文件
  27. event
  28. event:generate Generate the missing events and listeners based on registration
  29. key
  30. key:generate # 生成一个随机的 key,并自动更新到 config/app.php 的 key 键值对
  31. make
  32. make:auth # 快速构建登录注册功能,生成基本的登录注册视图,路由等
  33. make:command Create a new Artisan command
  34. make:controller Create a new controller class
  35. make:event Create a new event class
  36. make:factory Create a new model factory
  37. make:job Create a new job class
  38. make:listener Create a new event listener class
  39. make:mail Create a new email class
  40. make:middleware Create a new middleware class
  41. make:migration Create a new migration file
  42. make:model Create a new Eloquent model class
  43. make:notification Create a new notification class
  44. make:policy Create a new policy class
  45. make:provider Create a new service provider class
  46. make:request Create a new form request class
  47. make:resource Create a new resource
  48. make:rule Create a new validation rule
  49. make:seeder Create a new seeder class
  50. make:test Create a new test class
  51. migrate
  52. migrate # 运行一次迁移
  53. migrate:fresh # 直接drop掉table然后重置,注意与resfresh的区别
  54. migrate:install # 初始化迁移数据表
  55. migrate:refresh # 根据迁移文件中down方法重置,并重新执行所有的数据迁移
  56. migrate:reset # 回滚所有的数据迁移
  57. migrate:rollback # 回滚最近一次数据迁移
  58. migrate:status # 显示每一次迁移的状态
  59. notifications
  60. notifications:table Create a migration for the notifications table
  61. package
  62. package:discover Rebuild the cached package manifest
  63. queue
  64. queue:failed List all of the failed queue jobs
  65. queue:failed-table Create a migration for the failed queue jobs database table
  66. queue:flush Flush all of the failed queue jobs
  67. queue:forget Delete a failed queue job
  68. queue:listen Listen to a given queue
  69. queue:restart Restart queue worker daemons after their current job
  70. queue:retry Retry a failed queue job
  71. queue:table Create a migration for the queue jobs database table
  72. queue:work Start processing jobs on the queue as a daemon
  73. route
  74. route:cache # 生成bootstrap/cache/routes.php文件,提高路由效率,注意路由缓存不会随着更新而自动重载,开发时候建议关闭
  75. route:clear # 清除生成的路由缓存
  76. route:list # 展示所有路由信息
  77. schedule
  78. schedule:run Run the scheduled commands
  79. session
  80. session:table Create a migration for the session database table
  81. storage
  82. storage:link Create a symbolic link from "public/storage" to "storage/app/public"
  83. vendor
  84. vendor:publish # 开发包的时候,将包中文件根据你的设置发布到laravel工程对应目录
  85. view
  86. view:clear # 清除storage/framework/views文件夹下的视图缓存文件
  1. # 一些常用命令
  2. php artisan make:controller IndexController   # 大驼峰写法
  3. php artisan make:model Models/UserAccount  # 可以指定目录,单数大驼峰写法
  4. php artisan make:migration create_user_accounts_table --create=user_accounts # 蛇形复数写法
  5. php artisan make:model UserAccount -m  # 生成model和数据迁移文件 大驼峰单数写法
  6. php artisan make:seeder StudentsTableSeeder
  7. php artisan db:seed --class=StudentsTableSeeder
  8. php artisan version # 显示当前使用的 Laravel 版本
  9. # 关于缓存的命令
  10. php artisan optimize # 在bootstrap/cache/下生成packages.php ,services.php文件
  11. php artisan clear-compiled # optimize操作的反向
  12. php artisan config:cache
  13. php artisan config:clear
  14. php artisan route:cache
  15. php artisan route:clear
  16. php artisan view:clear

2. 编写命令

2.1 构建自己的命令

命令默认存储在app/Console/Commands目录,可以通过以下方法生成命令文件

  1. php artisan make:command SendEmails

文件内容

  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\User;
  5. class SendEmails extends Command
  6. {
  7. // 1. 命令, php artisan list 会显示
  8. protected $signature = 'command:send_email {user_id}';
  9. // 2. 命令的描述, php artisan list 会显示
  10. protected $description = 'send an email to user. eg: php artisan command:send_email 1';
  11. public function __construct()
  12. {
  13. parent::__construct();
  14. }
  15. // 3. 命令的逻辑
  16. public function handle()
  17. {
  18. // 通过$this->argument()命令的参数
  19. $user =User::find($this->argument('user_id'));
  20. dd($user);
  21. // 给该用户发送邮件的逻辑
  22. }
  23. }

使用方法

  1. php artisan command:sen_email 1

2.2 闭包命令

首先查看 app/Console/Kernel.php,commands方法分别加载了自建命令文件和闭包命令

  1. protected function commands()
  2. {
  3. //1. 加载 Commands里面的文件,也就是我们使用命令创建的文件
  4. $this->load(__DIR__.'/Commands');
  5. //2. 加载 reoute/console.php里面的闭包命令
  6. require base_path('routes/console.php');
  7. }

打开routes/console.php

  1. <?php
  2. use Illuminate\Foundation\Inspiring;
  3. //command 方法接收两个参数:命令签名 和一个接收命令参数和选项的闭包:
  4. Artisan::command('inspire', function () {
  5. $this->comment(Inspiring::quote());
  6. })->describe('Display an inspiring quote');

发现inspire命令在此定义,测试下,发现会输出一句名言

  1. $ php artisan inspire
  2. He who is contented is rich. - Laozi

自己创建一个闭包命令试试

  1. Artisan::command('build {project}', function ($project) {
  2. $this->info("Building {$project}!");
  3. })->describe('Build the project');

测试

  1. $ php artisan build test
  2. Building test!

3. 定义输入期望

通过设置app/Console/Commands/xxx.php中的signature属性来定义

  1. 参数

    形式:{xxx} ,用花括号包起来
  1. // 必须参数
  2. protected $signature = 'email:send {user}';
  3. // 可选参数...
  4. protected $signature = 'email:send {user?}''
  5. // 带有默认值的可选参数...
  6. protected $signature = 'email:send {user=foo}''
  1. 选项

形式:{--xxx} , -- 作为前缀,并用花括号包裹

  1. // 开关选项 --queue 开关被传递,该选项的值为 true ,否则为 false
  2. protected $signature = 'email:send {user} {--queue}';
  3. // 带值的选项 queue的值为传递的值
  4. protected $signature = 'email:send {user} {--queue=}';
  5. // 带默认值的选项
  6. protected $signature = 'email:send {user} {--queue=default}';
  7. // 选项简写
  8. rotected $signature = 'email:send {user} {--Q|queue}'
  1. 输入数组
  1. // php artisan email:send foo bar
  2. // 则user的值为['foo', 'bar']
  3. rotected $signature = 'email:send {user*}'
  4. // 在定义期望数组输入的选项时,传递给命令的每个选项值都应以选项名称为前缀:
  5. // php artisan email:send --id=1 --id=2
  6. email:send {user} {--id=*}
  1. 输入说明

你可以通过冒号为输入参数和选项分配说明文字。如果你需要一点额外的空间来定义你的命令,可以随意将多个行分开:

  1. protected $signature = 'email:send
  2. {user : The ID of the user}
  3. {--queue= : Whether the job should be queued}';

4.I/O 命令

  1. 检索输入
  1. // 检索特定参数
  2. $userId = $this->argument('user');
  3. // 所有参数 以 array 检索
  4. $arguments = $this->arguments();
  5. // 检索特定选项...
  6. $queueName = $this->option('queue');
  7. // 检索所有选项...
  8. $options = $this->options();

如果参数或选项不存在,则返回 null

  1. 交互式输入
  1. // ask 方法将提示用户给定问题,接收他们的输入,然后将用户的输入返回到你的命令:
  2. $name = $this->ask('What is your name?');
  3. // 类似于ask方法,但是输入内容不可见
  4. $password = $this->secret('What is the password?');
  5. // 请求确认,默认情况下,该方法将返回 false。但是,如果用户根据提示输入 y 或者 yes 则会返回 true。
  6. if ($this->confirm('Do you wish to continue?')) {
  7. //
  8. }
  9. // 自动补全 不管提示的内容是什么,用户仍然可以选择任何回答
  10. $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
  11. //给用户提供预定义的一组选择,可以使用 choice 方法。如果用户未选择任何选项,你可以返回设置的默认值:
  12. $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);
  1. 编写输出
  • 普通信息

    可以使用 line 、info 、 comment 、 question 和 error 方法来将输出发送到终端。每个方法都有适当的 ANSI 颜色来作为表明其目的。
  1. $this->info('Display this on the screen');
  2. $this->error('Something went wrong!');
  3. $this->line('Display this on the screen');
  • table表布局
  1. $headers = ['Name', 'Email'];
  2. $users = App\User::all(['name', 'email'])->toArray();
  3. $this->table($headers, $users);
  • 进度条

首先,定义进程将遍历的步骤总数。然后,在处理每个项目后推进进度栏

  1. $users = App\User::all();
  2. $bar = $this->output->createProgressBar(count($users));
  3. foreach ($users as $user) {
  4. $this->performTask($user);
  5. $bar->advance();
  6. }
  7. $bar->finish();

5. 注册命令

  • 方法1 在commans方法中载入目录

app/Console/Commands 目录下的所有命令都将自动注册到 Artisan。 实际上,你可以自由地调用 load 方法来扫描 Artisan 命令的其他目录:

  1. /**
  2. * 注册应用程序的命令。
  3. *
  4. * @return void
  5. */
  6. protected function commands()
  7. {
  8. $this->load(__DIR__.'/Commands');
  9. $this->load(__DIR__.'/MoreCommands');
  10. // ...
  11. }
  • 方法2 定义$commands属性

类名添加到 app/Console/Kernel.php 文件的 $command 属性来手动注册命令。当 Artisan 启动时,该属性中列出的所有命令将由 服务容器 解析并在 Artisan 注册:

  1. protected $commands = [
  2. Commands\SendEmails::class
  3. ];

6. 调用命令

  1. 在CLI之外执行命令,可以通过call方法,比如在控制器或者路由触发
  1. Route::get('/foo', function () {
  2. $exitCode = Artisan::call('email:send', [
  3. 'user' => 1, '--queue' => 'default'
  4. ]);
  5. //
  6. });
  1. 将Artisan命令交给队列处理

需要确保队列已经正确配置,并运行了队列监听器

  1. Route::get('/foo', function () {
  2. Artisan::queue('email:send', [
  3. 'user' => 1, '--queue' => 'default'
  4. ]);
  5. //
  6. });
  1. 如果有不是字符串的选项,比如true或false
  1. $exitCode = Artisan::call('migrate:refresh', [
  2. '--force' => true,
  3. ]);
  1. 其它命令调用命令

从现有的 Artisan 命令中调用其它命令。你可以使用 call 方法

  1. public function handle()
  2. {
  3. $this->call('email:send', [
  4. 'user' => 1, '--queue' => 'default'
  5. ]);
  6. //
  7. }

如果要调用另一个控制台命令并阻止其所有输出,可以使用 callSilent 方法。

  1. $this->callSilent('email:send', [
  2. 'user' => 1, '--queue' => 'default'
  3. ]);

laravel5.5artisan命令的更多相关文章

  1. Laravel5 (cli)命令行执行脚本及定时任务

    Artisan是Laravel自带的命令行接口名称,它提供了很多有用的命令想要查看所有可用的Artisan命令,可使用list命令查看: 1 php artisan list 每个命令都可以用help ...

  2. Laravel5.0学习--03 Artisan命令

    本文以laravel5.0.22为例. 简介 Artisan 是 Laravel 内置的命令行接口.它提供了一些有用的命令协助您开发,它是由强大的 Symfony Console 组件所驱动.利用它, ...

  3. 安装laravel5.1项目命令

    作为程序员还有什么比命令行执行效率还要快的呢,哈哈... composer create-project laravel/laravel your-project-name --prefer-dist ...

  4. laravel5.5通过Migrations修改表 的artisan命令

    1,不同表的修改都需要通过命令创建一个文件 2,首先通过artisan创建对应表的一个文件 php artisan make:module:migration abtinvitcard(模块名) al ...

  5. Laravel5.5执行表迁移命令出现表为空的解决方案

    今天在使用一个第三方包 laravel-admin 时,出现了这样的错误:SQLSTATE[42000]: Syntax error or access violation: 1103 Incorre ...

  6. laravel5.1学习(2)-- artisan tinker命令

    例如:为users表创建20条测试输入 G:\wamp\www\hcmf>php artisan tinker >>> namespace App; => null &g ...

  7. laravel5.8笔记三:常用命令

    创建控制器 php artisan make:controller Index/IndexController 创建模型 php artisan make:model Index/IndexContr ...

  8. 【laravel5.4】php artisan 常用命令

        路由缓存:/www/wd***/php/bin/php artisan route:cache 查看全部路由并输出到txt文件:/www/wd***/php/bin/php artisan r ...

  9. laravel5 数据库配置(MySQL)

    laravel5 数据库配置(MySQL) 首先有一个安装完成可以运行的laravel框架. 配置database.php 进入laravel根目录. 在config目录下找到database.php ...

随机推荐

  1. python数组列表、字典、拷贝、字符串

    python中字符串方法 name = "I teased at life as if it were a foolish game" print(name.capitalize( ...

  2. sql:表中数据全部删除之后,重新插入时,从1开始增加

    数据库中设置了自增列,有时候需要清楚数据库从新录入数据.最常见的做法就是使用sql语句"delete 表明名"或是直接选中数据,然后删除数据.但是再次插入数据的时候,你就会发现自增 ...

  3. Linux修改文件permission可执行属性

    列出文件属性 ls -al 修改文件属性为可读.可写 sudo chmod -c 777 <your file name>

  4. Ubuntu 如何将桌面上的Home中的文件夹除去

    安装Ubuntu后, 由于无法用Terminal(终端)进入带中文的文件夹,会引起很多操作不便.很多朋友想到了将它们都改成中文,但是当再次开机重启使却会发现,原本光洁的桌面现在竟然出现了一堆文件夹?? ...

  5. OJ网站

    没事做做题是打发时间的好办法,还能练习下思维,效益很不错,但就是耗时 就选了3个oj,多了眼花缭乱 https://www.vijos.org/ http://uoj.ac/ https://leet ...

  6. MHA启动及关闭

    MHA启动及关闭 #masterha_manager --global_conf=/etc/masterha/masterha_default.conf --conf=/etc/masterha/ap ...

  7. Shiro Demo:SpringBoot+Shiro+Druid+MyBatis

    访问start.spring.io生成项目: 然后选择依赖: pom.xml: <?xml version="1.0" encoding="UTF-8"? ...

  8. 内置函数SQLCODE和SQLERRM的使用

    由于ORACLE的错信息最大长度是512字节,为了得到完整的错误提示信息,我们可用 SQLERRM 和 SUBSTR 函数一起得到错误提示信息,方便进行错误,特别是如果WHEN OTHERS异常处理器 ...

  9. 小程序navigateTo和redirectTo的使用

    最近公司商城项目,有个小问题,就是在商品详情页>购物车页>确认下单页>支付成功和取消支付都会前往订单详情页.当时我没想这么多就全部跳转都用了navigateTo,这样做的话,第一个问 ...

  10. 解决mysql远程连接失败的问题

    问题描述 在我远程连接我的服务器数据库的时候,navicat给我提示了这么一个错误: ERROR : Host 'xxx' is not allowed to connect to thisMySQL ...