添加 Lumen 没有的 key:generate 命令

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

1
2
cd app/Console
vim Kernel.php
1
2
3
4
protected $commands = [
// ...
\App\Console\Commands\KeyGenerateCommand::class // 添加此行
];

app/Console/Commands/KeyGenerateCommand.php

1
2
cd app/Console/Commands
vim KeyGenerateCommand.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?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.'),
);
}
}
本站文章除注明外均采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议进行许可 ヾ(゚ー゚ヾ)
分享到