Laravel

Lumen 添加没有的 key:generate 命令

文 / 管理员 来源 / 原创 阅读 / 914 3年前

Lumen is a stunningly fast micro-framework by Laravel.

.env 文件中需要配置 APP_KEY=,想通过和 Laravel 相同的方式随机生成一个 KEY,执行命令 artisan key:generate 结果却是 Command is not defined.,那就需要自己加一个 key:generate 功能


第一步:编辑 app/Console/Kernel.php

protected $commands = [
    // ...
    \App\Console\Commands\KeyGenerateCommand::class // 添加此行
];

第二步:编辑app/Console/Commands/KeyGenerateCommand.php  (如果没有就新建这个文件)

<?php
namespace App\Console\Commands;

use Illuminate\Support\Str;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class KeyGenerateCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'key:generate';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Set the application key";
    
    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $key = $this->getRandomKey();
        if ($this->option('show')) {
            $this->line('<comment>'.$key.'</comment>');
            return;
        }
        $path = base_path('.env');
        if (file_exists($path)) {
            file_put_contents(
                $path,
                str_replace(
                    'APP_KEY=' . env('APP_KEY'),
                    'APP_KEY=' . $key,
                    file_get_contents($path)
                )
            );
        }
        $this->info("Application key [$key] set successfully.");
    }
    
    /**
     * Generate a random key for the application.
     *
     * @return string
     */
    protected function getRandomKey()
    {
        return Str::random(32);
    }
    
    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('show', null, InputOption::VALUE_NONE, 'Simply display the key instead of modifying files.'),
        );
    }
}


评论

共0条评论
  • 这篇文章还没有收到评论,赶紧来抢沙发吧~

站点声明:本站转载作品版权归原作者及来源网站所有,原创内容作品版权归作者所有,任何内容转载、商业用途等均须联系原作者并注明来源。

© 2020-2030 qdxcy.cn 版权所有京ICP备13045222号
相关侵权、举报、投诉及建议等,请发E-mail:2323946929@qq.com

友情链接: YzmCMS官方网站 YzmCMS官方论坛