1. 将本文中的类文件以文件名 myUrlManager.php 保存到应用程序的protected/components/目录中
2. 修改配置文件:protected/config/main.php 在components项中增加:
'urlManager' => array(
'class' => 'myUrlManager',
),
表示要使用我们自定义的类解析路由
使用中如有任何问题,请联系 zhangxugg@163.com获取帮助。
3. 部署成功,现在可以直接在命令行下运行WEB控制器了:
php index.php [controllerId/ActionId] [arg1=value1] [arg2=value2] ...
如果不提供控制器,表示运行默认的控制器
如果不提供动作名,表示运行控制器的默认动作
[arg1=value1] [arg2=value2] ... 实际上解析为:$_GET['arg1'] = value1; $_GET['arg2'] = value2;
protected/components/myUrlManager.php文件的内容:
<?php
/**
* myUrlManager class file.
*@author zhangxugg@163.com 2015-2-5
*@copyright zhangxugg@163.com
*
* This class is used for CLI route parse. you can run the web controller
* and it's action from CLI
* usage: php index.php [path/to/controllerId/actionId] [arg1=value1] [arg2=value2] ...
* php index.php => http://hostname/index.php
* php index.php controllerId/action => http://hostname/index.php?r=controllerId/action
* php index.php path/controllerId/action foo=a bar=b => /index.php?r=path/controllerId/action&foo=a&bar=b
*
*/
class myUrlManager extends CUrlManager {
public function parseUrl($request){
if(isset($_SERVER['HTTP_HOST'])) {
return parent::parseUrl($request);
}
if(!isset($_SERVER['argv'][1])) {
return '';
}
if(preg_match('|^[\w/]+$|i',$_SERVER['argv'][1]) ) {
$_GET[$this->routeVar] = $_SERVER['argv'][1];
}
$argsFrom = $_GET[$this->routeVar] ? 2 : 1;
foreach($_SERVER['argv'] as $i => $val) {
if($i< $argsFrom) continue;
if(!preg_match('/^([a-zA-z\w]+)=(.+)/',$val,$args)) {
$this->printHelp();
exit;
}else{
$_GET[$args[1]] = $args[2];
}
}
return $_GET[$this->routeVar];
}
public function printHelp() {
echo "usage: ";
echo $_SERVER['argv'][0];
echo "[path/to/controllerId][/actionId] arg1=value1 arg2=value2 ...\n";
echo "equals to ?r=path/to/controllerId/actionId&arg1=value2&arg2=value2";
}
}