栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

SWOOLE 从入门到放弃之写个小框架(八)

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SWOOLE 从入门到放弃之写个小框架(八)

突然想开个视频,传上来挣点奶粉钱。不知道可不可行,@慕女神,你就说行不行吧。。

撸代码。

前几篇内容已经能成功的跑起来,但它只是能跑起来,除此之外,没屁用。浏览器输入http://xxxx:9501/XXXX或http://xxxx:9501/YYYY,它没什么变化,这就是个勺子(注:陕西方言中傻子的意思,请看电影《一个勺子》)。接下来就先让它能给大家有个正常人能有的反应。。

首先,客户端发起请求时程序得指路,还得指到对的地方,这就是路由的基础功能了。而且我想给它定个目录稍高那么一丢丢。
一、能定义默认访问地址,就是它的默认首页。
二、咱还能给它来个伪扩展,比如“.html”或者是".lmth"。
三、有些地址太长,还能给它缩短一些。
四、让URL好看一些,比如/user/info.html?uid=1,变身后就 /user/info/1.html,是不是很好看。
五、开写。

创建文件 frame/Lib/Router.php,贴代码

 'index',     //默认模块
 'c'      => 'index',     //默认控制器
 'a'      => 'init',     //默认操作
 'ext'    => '.html',   //url后缀    例如 .html
 'rules'  =>  [    //自定义路由
     'user'  => 'uesr/index/init',
     'login' => 'index/login/init',
 ]
    ];
    private function __construct() {}
    
    public static function get_instance() {
 if( is_null(self::$instance) ) {
     self::$instance = new self();
 }
 return self::$instance;
    }

    
    public function http($request_uri){
 $param      = [];
 $module     = self::$config['m'];
 $controller =  self::$config['c'];
 $action     =  self::$config['a'];

 if(empty($request_uri)) {
     return ['m'=>$module ,'c'=>$controller,'a'=>$action,'p'=>$param];
 }

 $path = trim($request_uri, '/');
 if(!empty( self::$config['ext']) ){
     $path = rtrim ($path,self::$config['ext']);
 }

 if (!empty(self::$config['rules']) ) {
     foreach (self::$config['rules'] as $key => $value) {
  if(substr($path,0,strlen($key)) == $key) {
      $path = str_replace($key, $value, $path);
      break;
  }
     }
 }

 $param = explode( "/" , $path);
 !empty($param[0]) && $module = $param[0];
 isset($param[1]) && $controller = $param[1];
 isset($param[2]) && $action = $param[2];

 if(count($param)>=3){
     $param = array_slice($param, 3);
 }else{
     $param = array_slice($param, 2);
 }

 return ['m'=>$module ,'c'=>$controller,'a'=>$action,'p'=>$param];
    }
}

改App.php代码,测试路由。

public function http($request,$response){
 $req = Request::get_instance ();
 $req->set($request);
 $router = Router::get_instance ()->http($req->server['request_uri']);
 $response->end(var_export ($router,TRUE));
    }

启动start.php

看效果
URL:http://192.168.1.111:9501/

URL: http://192.168.1.111:9501/index/index/index/1

OK。。

吃饭,午睡,下午再更

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/229568.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号