zoukankan      html  css  js  c++  java
  • laravel5.5artisan命令

    1. 简介

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

    查看所有可用命令列表

    php artisan list
    
    Available commands:
        clear-compiled       # optimize操作的反向,清除生成的文件
        down                 # 将站点设为维护状态
        env                  # 显示项目现在运行所处的环境(local或其他)
        help                 # 帮助信息
        inspire              # 输出一句名言,位于routes/console.php
        list                 # 列出所有命令
        migrate              # 运行迁移文件
        optimize             # 优化应用程序性能,生成自动加载文件,先要运行config:cache命令
        preset               Swap the front-end scaffolding for the application
        serve                # 使用 PHP 内置的开发服务器启动应用 【要求 PHP 版本在 5.4 或以上】
        tinker               # 进入与当前应用环境绑定的 REPL 环境,相当于 Rails 框架的 rails console 命令
        up                   # 将站点设回可访问状态
    app
        app:name             # 设置应用程序命名空间
    auth
        auth:clear-resets    # 清除过期的密码重置密钥
    cache
        cache:clear          # 清除应用程序缓存
        cache:forget         Remove an item from the cache
        cache:table          # 创建一个缓存数据库表的迁移
    config
        config:cache         # 生成文件 bootstrap/cache/config.php,把 config 文件夹里所有配置信息合并到一个文件里,减少运行时文件的载入数量,不会自动重载,开发时候建议关闭
        config:clear         # 清除缓存的config.php文件
    db
        db:seed              # 生成测试数据文件
    event
        event:generate       Generate the missing events and listeners based on registration
    key
        key:generate         # 生成一个随机的 key,并自动更新到 config/app.php 的 key 键值对
    make                   
        make:auth            # 快速构建登录注册功能,生成基本的登录注册视图,路由等
        make:command         Create a new Artisan command
        make:controller      Create a new controller class
        make:event           Create a new event 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: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              # 运行一次迁移
        migrate:fresh        # 直接drop掉table然后重置,注意与resfresh的区别
        migrate:install      # 初始化迁移数据表
        migrate:refresh      # 根据迁移文件中down方法重置,并重新执行所有的数据迁移
        migrate:reset        # 回滚所有的数据迁移
        migrate:rollback     # 回滚最近一次数据迁移
        migrate:status       # 显示每一次迁移的状态
    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          # 生成bootstrap/cache/routes.php文件,提高路由效率,注意路由缓存不会随着更新而自动重载,开发时候建议关闭
        route:clear          # 清除生成的路由缓存
        route:list           # 展示所有路由信息
    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       # 开发包的时候,将包中文件根据你的设置发布到laravel工程对应目录
    view
        view:clear           # 清除storage/framework/views文件夹下的视图缓存文件
    
    # 一些常用命令
    php artisan make:controller IndexController   # 大驼峰写法
    php artisan make:model Models/UserAccount   # 可以指定目录,单数大驼峰写法
    php artisan make:migration create_user_accounts_table --create=user_accounts  # 蛇形复数写法
    php artisan make:model UserAccount -m   # 生成model和数据迁移文件 大驼峰单数写法
    php artisan make:seeder StudentsTableSeeder 
    php artisan db:seed --class=StudentsTableSeeder
    php artisan –version # 显示当前使用的 Laravel 版本
    
    
    # 关于缓存的命令 
    php artisan optimize        # 在bootstrap/cache/下生成packages.php ,services.php文件
    php artisan clear-compiled  # optimize操作的反向
    
    php artisan config:cache
    php artisan config:clear
    
    php artisan route:cache
    php artisan route:clear
    
    php artisan view:clear
    

    2. 编写命令

    2.1 构建自己的命令

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

    php artisan make:command SendEmails
    

    文件内容

    <?php
    
    namespace AppConsoleCommands;
    
    use IlluminateConsoleCommand;
    use AppUser;
    
    class SendEmails extends Command
    {
    
        // 1. 命令, php artisan list 会显示
        protected $signature = 'command:send_email {user_id}';
        
        // 2. 命令的描述, php artisan list 会显示
        protected $description = 'send an email to user. eg: php artisan command:send_email 1';
    
        public function __construct()
        {   
            parent::__construct();
        }
    
        // 3. 命令的逻辑
        public function handle()
        {   
            // 通过$this->argument()命令的参数
            $user =User::find($this->argument('user_id'));
            dd($user);
            
            //  给该用户发送邮件的逻辑
        }
    }
    

    使用方法

    php artisan command:sen_email 1
    

    2.2 闭包命令

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

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

    打开routes/console.php

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

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

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

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

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

    测试

    $ php artisan build test
    Building test!
    

    3. 定义输入期望

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

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

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

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

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

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

    4.I/O 命令

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

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

    1. 交互式输入
    // ask 方法将提示用户给定问题,接收他们的输入,然后将用户的输入返回到你的命令:
    $name = $this->ask('What is your name?');
    
    // 类似于ask方法,但是输入内容不可见
    $password = $this->secret('What is the password?');
    
    // 请求确认,默认情况下,该方法将返回 false。但是,如果用户根据提示输入 y 或者 yes 则会返回 true。
    if ($this->confirm('Do you wish to continue?')) {
        //
    }
    
    // 自动补全  不管提示的内容是什么,用户仍然可以选择任何回答
    $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);
    
    //给用户提供预定义的一组选择,可以使用 choice 方法。如果用户未选择任何选项,你可以返回设置的默认值:
    $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], $default);
    
    1. 编写输出
    • 普通信息
      可以使用 line 、info 、 comment 、 question 和 error 方法来将输出发送到终端。每个方法都有适当的 ANSI 颜色来作为表明其目的。
    $this->info('Display this on the screen');
    $this->error('Something went wrong!');
    $this->line('Display this on the screen');
    
    • table表布局
    $headers = ['Name', 'Email'];
    
    $users = AppUser::all(['name', 'email'])->toArray();
    
    $this->table($headers, $users);
    
    • 进度条

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

    $users = AppUser::all();
    
    $bar = $this->output->createProgressBar(count($users));
    
    foreach ($users as $user) {
        $this->performTask($user);
    
        $bar->advance();
    }
    
    $bar->finish();
    

    5. 注册命令

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

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

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

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

    protected $commands = [
        CommandsSendEmails::class
    ];
    

    6. 调用命令

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

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

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

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

    public function handle()
    {
        $this->call('email:send', [
            'user' => 1, '--queue' => 'default'
        ]);
    
        //
    }
    

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

    $this->callSilent('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);
    
  • 相关阅读:
    WCF 第四章 绑定 在多个绑定上暴露一个服务契约
    WCF 第五章 行为 事务跨操作事务流
    WCF 第五章 导出并发布元数据(服务行为)
    WCF 第五章 行为 通过配置文件暴露一个服务行为
    WCF 第五章 不支持会话的绑定的默认并发和实例
    WCF 第五章 并发和实例(服务行为)
    WCF 第五章 行为 总结
    WCF 第四章 绑定 绑定元素
    WCF 第五章 行为 事务之选择一个事务协议OleTx 或者WSAT
    WCF 第四章 绑定 比较各种绑定的性能和可扩展性
  • 原文地址:https://www.cnblogs.com/redirect/p/8658755.html
Copyright © 2011-2022 走看看