整理Yii Console
一些用法和問題
- Console Applicaton 配置和運行
- 如何實現接收原始參數?
- 如何實現終端等待輸入,輸入確認?
在框架根目錄,有文件名稱為 yii
,可以在命令行模式運行。
#!/usr/bin/env php
<?php
/**
* Yii console bootstrap file.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/vendor/autoload.php');
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php');
// 配置文件位置
$config = require(__DIR__ . '/config/console.php');
//console application實例
$application = new yii\console\Application($config);
$exitCode = $application->run();
exit($exitCode);
整理等待輸入,輸入確認用法。yii\helpers\BaseConsole
是終端的幫助類,處理命令行輸入,輸出。
namespace app\commands;
use Yii;
class HelloController extends Controller
{
/**
* This command echoes what you have entered as the message.
* @param string $message the message to be echoed.
*/
public function actionIndex($message = 'hello world')
{
//Yii方式接收參數
echo $message . "\n";
try {
var_dump($argv);
} catch (\Exception $e) {
echo $e->getMessage(); //Undefined variable: argv
}
//接收原始命令行參數
global $argv;
var_dump($argv);
//輸入提示符
$name = \yii\helpers\BaseConsole::input("輸入姓名: ");
$age = \yii\helpers\BaseConsole::prompt("輸入年齡: ", ['default' => 20]);
if(!$this->confirm("確定輸入正確嗎?")) {
exit("退出\n");
}
echo "你輸入的姓名是:$name\n";
echo "你輸入的年齡是:$age\n";
}
}
終端輸出
# 提示輸入,確認輸入
php yii hello
輸入姓名: 小明
輸入年齡: [20] 10
確定輸入正確嗎? (yes|no) [no]:yes
你輸入的姓名是:小明
你輸入的年齡是:10
# $argv
php yii hello msg
array(2) {
[0]=>
string(3) "yii"
[1]=>
string(5) "hello"
[2]=>
string(3) "msg"
}
...