1. Go to this page and download the library: Download kode/console library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kode / console example snippets
use Kode\Console\Command;
use Kode\Console\Input;
use Kode\Console\Output;
class HelloCommand extends Command
{
public function __construct()
{
parent::__construct(
'hello', // 命令名
'输出问候语', // 描述
'hello {name?} {--upper:bool}' // 签名
);
$this->sig($this->usage);
}
public function fire(Input $in, Output $out): int
{
$name = $in->arg(0, 'World');
$upper = $in->flag('upper');
$greeting = "Hello, {$name}!";
if ($upper) {
$greeting = strtoupper($greeting);
}
$out->success($greeting);
return 0; // 返回 0 表示成功
}
}
ode\Console\Kernel;
$kernel = new Kernel();
$kernel->add(HelloCommand::class);
exit($kernel->boot($argv));
use Kode\Console\CommandGroup;
// 创建命令组
$databaseGroup = new CommandGroup('database', '数据库操作');
$databaseGroup->addCommand(new MigrateCommand());
$databaseGroup->addCommand(new SeedCommand());
$kernel->addGroup($databaseGroup);
use Kode\Console\Contract\IsMiddleware;
class TimingMiddleware implements IsMiddleware
{
public function handle(Input $in, Output $out, callable $next): int
{
$start = microtime(true);
$result = $next($in, $out);
$duration = round((microtime(true) - $start) * 1000, 2);
$out->line("\n执行时间: {$duration}ms", 'gray');
return $result;
}
}
$kernel->addMiddleware(new TimingMiddleware());
use Kode\Console\EventManager;
use Kode\Console\Event;
$eventManager = new EventManager();
// 监听事件
$eventManager->listen('command.executing', function (Event $event) {
echo "即将执行: {$event->data['command']->name}\n";
});
$kernel->setEventManager($eventManager);