创建命令,通过 php artisan init:user 执行
php artisan make:command InitUser --command=init:user
php artisan list
所有 Laravel 应用都包含了 Tinker,一个基于 PsySH 包提供支持的 REPL 。Tinker 让你可以在命令行中与你整个的 Laravel 应用进行交互 。 包括 Eloquent ORM、任务、事件等等。运行 Artisan 命令 tinker 进入 Tinker 环境:
php artisan tinker
命令白名单
Tinker 通过采用白名单的方式来确定允许哪些 Artisan 命令可以在 shell 中运行。默认情况下,你可以运行 clear-compiled 、down、env、 inspire、migrate、 optimize、和 up 命令。如果你想要添加更多的白名单命令,可以将它们添加到 tinker.php 配置文件中的 commands 数组里:
'commands' => [ // App\Console\Commands\ExampleCommand::class, ],
黑名单别名
通常,Tinker 会在 Tinker 中根据你的需要自动为类添加别名。然而,你可能不希望为某些类添加别名。你可以在 tinker.php 配置文件中的 dont_alias 数组里列举这些类来完成此操作:
'dont_alias' => [ App\User::class, ],
php artisan list test test:test Command description
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test:test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
echo time();
}
}命令中的 handle 可以依赖注入,也可以注入自己的类,例如
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
class test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test:test';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(Request $request)
{
var_dump(time());
var_dump($request->method());
var_dump($request->getClientIp());
}
}运行结果:
E:\phpStudy\WWW\laravel_admin>php artisan test:test
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:41:
int(1565759750)
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:42:
string(3) "GET"
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:43:
string(9) "127.0.0.1"
命令行中传递参数
所有用户提供的参数及选项都被包含在花括号中。在下面的例子中,这个命令定义了一个 必须的参数: user:
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'email:send {user}';你也可以创建可选参数,并定义参数的默认值:
// 可选参数...
email:send {user?}// 带有默认值的可选参数...
email:send {user=foo}选项
选项,类似于参数,是用户输入的另一种格式。
当命令行指定选项时,它们以两个连字符 ( -- ) 作为前缀。
有两种类型的选项:接收值和不接收值。
不接收值的选项就像是一个布尔值的「开关」。
让我们看一下这种类型的选项的例子:
/**
* 命令行的名称及签名。
*
* @var string
*/
protected $signature = 'email:send {user} {--queue}';
在这个例子中,可以在调用 Artisan 命令时指定 --queue 开关。如果 --queue 开关被传递,该选项的值为 true, 否则为 false :
php artisan email:send 1 --queue带值的选项
接下来,让我们来看一个带值的选项。如果想让用户必须为选项指定一个值,则需要在选项名称末尾追加一个等号 = 作为的后缀:
/**
* 命令行的名称及签名。
*
* @var string
*/
protected $signature = 'email:send {user} {--queue=}';
在这个例子中, 用户可以传递该选项的值,如下所示:
php artisan email:send 1 --queue=default
你也可以通过在选项名称后面指定默认值来设定该选项的默认值。如果用户没有传递选项值,将使用设定的默认值:
email:send {user} {--queue=default}Command I/O
获取输入
在命令执行时,显然你需要获取命令接收到的参数和选项的值。你可以用 argument 和 option 方法来达到目的:
/**
* 执行命令。
*
* @return mixed
*/
public function handle()
{
$userId = $this->argument('user');
//
}如果你想所有的参数以 array 数组获取,可以调用 arguments 方法:
$arguments = $this->arguments();
和获取参数类似,option 方法可以非常容易的获取选项的值。要将所有的选项以数组获取,使用 options 方法:
// 获取一个指定的选项值
$queueName = $this->option('queue');// 获取所有的选项值
$options = $this->options();
如果参数或选项不存在,则返回 null 。
例如:
protected $signature = 'test:test {user}';
E:\phpStudy\WWW\laravel_admin>php artisan test:test
Not enough arguments (missing: "user").
protected $signature = 'test:test {user?}';
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:41:
int(1565760195)
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:42:
string(3) "GET"
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:43:
string(9) "127.0.0.1"实例:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
class test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test:test {user}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(Request $request)
{
var_dump('获取命令行上的值' . $this->argument('user'));
//var_dump(time());
//var_dump($request->method());
//var_dump($request->getClientIp());
}
}
E:\phpStudy\WWW\laravel_admin\app\Console\Commands\test.php:41:
string(25) "获取命令行上的值1"
public function handle(Request $request)
{
var_dump('获取命令行上的值' . $this->argument('user'));
$name =$this->ask('what is you name:');
var_dump('您的名字叫:'.$name);
$password = $this->secret('What is the password?');
$this->error('这是密码,保密啊'.$password);
$name = $this->anticipate('What is your name?', ['james', 'songyongzhan']);
$this->info('info:'.$name);
$this->line('line(:'.$name);
$this->comment('comment:'.$name);
$this->question('question:'.$name);
$this->error('error:'.$name);
//var_dump(time());
//var_dump($request->method());
//var_dump($request->getClientIp());
}带有进度条代码:
$bar=$this->output->createProgressBar(1000);
$bar->start();
for($i=1;$i<=1000;$i++){
//处理你的业务逻辑
$bar->advance();
usleep(500000);
}$bar->finish();
E:\phpStudy\WWW\laravel_admin>php artisan test:test 1
185/1000 [=====>----------------------] 18%
204/1000 [=====>----------------------] 20%
339/1000 [=========>------------------] 33%
903/1000 [=========================>--] 90%
E:\phpStudy\WWW\laravel_admin>php artisan test:test 1
1000/1000 [============================] 100%
E:\phpStudy\WWW\laravel_admin>
执行完毕
更详细文档参考:https://symfony.com/doc/current/components/console/helpers/progressbar.html
注册命令
app/Console/Commands 目录下的命令都会被注册,这是由于控制台内核的 commands 方法调用了 load。实际上,可随意调用 load 来扫描其他目录下的 Artisan 命令:
/**
* 注册应用的命令
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
$this->load(__DIR__.'/MoreCommands');
// ...
}也可以在 app/Console/Kernel.php 文件的 $commands 属性中手动注册命令的类名。Artisan 启动时,这个属性列出的命令都将由 服务容器 解析并通过 Artisan 进行注册:
protected $commands = [ Commands\SendEmails::class ];
程序调用命令 artisan 编写的命令,可以通过 路由的形式去调用
有了这样的方法,我们就可以通过url来控制代码去执行shell ,就可以做很多的事情了 o(* ̄︶ ̄*)o
有时需要在 CLI 之外执行 Artisan 命令,例如,在路由或控制器里触发 Artisan 命令。要实现调用,可以使用 Artisan 门面的 call 方法。call 方法的第一个参数接受命令名,第二个参数接受数组形式的命令参数。退出码将返回:
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});另外,你可以将整个 Artisan 命令作为字符串传递给 call 方法:
Artisan::call('email:send 1 --queue=default');
Artisan 门面的 queue 方法可以将 Artisan 命令队列化,交由 队列工作进程 进行后台处理。使用此方法之前,务必配置好队列以及运行队列监听器:
Route::get('/foo', function () {
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});你也可以指定 Artisan 命令派发的连接或任务:
Artisan::queue('email:send', [
'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');
传递数组值
如果定义了接受数组的选项,可以直接传递数组到该选项:
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--id' => [5, 13]
]);
});
http://localhost:8011/
命令行调用 是阻塞的,一直等待代码完成后结束
Route::get('/', function () {
echo 'wait....';
$exitCode = \Illuminate\Support\Facades\Artisan::call('test:test', [
'user' => 1
]);
var_dump($exitCode);
//return view('welcome');
});执行任务的时候,一定要注意web 最大执行时长,一般是30秒,如果没有设置,则会报超时。
命令的互相调用
call 方法可以实现调用其它 Artisan 命令。call 方法接受命令名和数组形式的选项:
/**
* 执行控制台命令
*
* @return mixed
*/
public function handle()
{
$this->call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
}如果要抑制控制台命令的所有输出,可以使用 callSilent 方法。callSilent 的使用方法同 call :
$this->callSilent('email:send', [
'user' => 1, '--queue' => 'default'
]);Available commands:
| 命令 | 中文 | English |
|---|---|---|
| clear-compiled | 删除已编译的类文件 | Remove the compiled class file |
| down | 将应用程序置于维护模式 | Put the application into maintenance mode |
| dump-server | 启动转储服务器以收集转储信息。 | Start the dump server to collect dump information. |
| 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 |
| optimize | 缓存框架引导程序文件 | Cache the framework bootstrap files |
| preset | 为应用程序交换前端脚手架 | Swap the front-end scaffolding for the application |
| serve | 在 PHP 开发服务器上提供应用程序 | Serve the application on the PHP development server |
| tinker | 与您的应用程序互动 | Interact with your application |
| up | 使应用程序退出维护模式 | Bring the application out of maintenance mode |
app
| 命令 | 中文 | English |
|---|---|---|
| app:name | 设置应用程序命名空间 | Set the application namespace |
auth
| 命令 | 中文 | English |
|---|---|---|
| auth:clear-resets | 刷新过期的密码重置令牌 | Flush expired password reset tokens |
cache
| 命令 | 中文 | English |
|---|---|---|
| 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
| 命令 | 中文 | English |
|---|---|---|
| config:cache | 创建缓存文件以加快配置速度 | Create a cache file for faster configuration loading |
| config:clear | 删除配置缓存文件 | Remove the configuration cache file |
db
| 命令 | 中文 | English |
|---|---|---|
| db:seed | 填充数据库 | Seed the database with records |
event
| 命令 | 中文 | English |
|---|---|---|
| event:generate | 根据注册生成缺少的事件和侦听器 | Generate the missing events and listeners based on registration |
key
| 命令 | 中文 | English |
|---|---|---|
| key:generate | 生成应用程序 key | Set the application key |
lang
| 命令 | 中文 | English |
|---|---|---|
| lang:publish | 将语言文件发布到资源目录 | publish language files to resources directory. |
make
| 命令 | 中文 | English |
|---|---|---|
| make:auth | --- | Scaffold basic login and registration views and routes |
| make:channel | 创建一个新的 channel 类 | Create a new channel class |
| make:command | 创建一个新的 Artisan 命令 | Create a new Artisan command |
| make:controller | 创建一个新的控制器类 | Create a new controller class |
| make:event | --- | 创建一个新的 event 类 |
| 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 | 创建一个新的 Eloquent 模型类 | 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:scaffold | 代码生成器 —— Laravel 5.x Scaffold Generator | Create a laralib scaffold |
| make:seeder | 创建一个新的 seeder 类 | Create a new seeder class |
| make:test | 创建一个新的测试类 | Create a new test class |
migrate
| 命令 | 中文 | English |
|---|---|---|
| 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
| 命令 | 中文 | English |
|---|---|---|
| notifications:table | 为通知表创建迁移 | Create a migration for the notifications table |
optimize
| 命令 | 中文 | English |
|---|---|---|
| optimize:clear | 删除缓存的引导程序文件 | Remove the cached bootstrap files |
package
| 命令 | 中文 | English |
|---|---|---|
| package:discover | 重建缓存的包清单 | Rebuild the cached package manifest |
queue
| 命令 | 中文 | English |
|---|---|---|
| queue:failed | 列出所有 failed 队列工作 | List all of the failed queue jobs |
| queue:failed-table | 为 failed 队列工作数据库表创建迁移 | Create a migration for the failed queue jobs database table |
| queue:flush | 刷新所有 failed 队列工作 | Flush all of the failed queue jobs |
| queue:forget | 删除 failed 队列工作 | Delete a failed queue job |
| queue:listen | 监听一个给定的队列 | Listen to a given queue |
| queue:restart | 在当前工作之后重新启动队列工作器守护程序 | Restart queue worker daemons after their current job |
| queue:retry | 重试 failed 队列作业 | 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
| 命令 | 中文 | English |
|---|---|---|
| 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
| 命令 | 中文 | English |
|---|---|---|
| schedule:run | 运行预定的命令 | Run the scheduled commands |
session
| 命令 | 中文 | English |
|---|---|---|
| session:table | 为会话数据库表创建迁移 | Create a migration for the session database table |
storage
| 命令 | 中文 | English |
|---|---|---|
| storage:link | 创建从 “公共 / 存储” 到 “存储 / 应用 / 公共” 的符号链接 | Create a symbolic link from "public/storage" to "storage/app/public" |
vendor
| 命令 | 中文 | English |
|---|---|---|
| vendor:publish | 从供应商包中发布任何可发布的资产 | Publish any publishable assets from vendor packages |
view
| 命令 | 中文 | English |
|---|---|---|
| view:cache | 编译所有应用程序的 Blade 模板 | Compile all of the application's Blade templates |
| view:clear | 清除所有编译的视图文件 | Clear all compiled view files |
laravel中有很多的命令行,php artisan 命令
常用的命令行有哪些?
php artisan make:migration alter_user_table
php artisan migrate
进行与laravel交互模式
php artisan tinker
app('Psr\Log\LoggerInterace')
返回实例对象