本文共 3232 字,大约阅读时间需要 10 分钟。
上一篇的时候大概说了自动加载。开始讲路由和配置,路由是自己写的,写的比较渣渣。不要笑哦!路由类在Composer中也有很多,可以直接拿过来用。配置也很简单。自己百度谷歌一下去吧!这里就不说了。为了方便学习,还是自己写一个。可以更好的理解。
function C ($type) { $file = YIN_PATH."/"."config/conf.php"; //echo $file; $data = include $file; return $data[$type];}
也可以Composer包中的配置类也可以。
namespace core\gzy;use core\lib\Route;use Noodlehaus\Config;class Gzy{ private $modules; //默认模块 private $controller; //默认控制器 private $action; //默认方法 private $conf; //配置文件 private $parm; public function __construct() { $this->conf = new Config(YIN_PATH. '/config/conf.php'); }
然后在 nginx 里配置:
location / { index index.php; try_files $uri $uri/ /index.php$is_args$args; #autoindex on; }
apache配置 可以在项目文件.htaccess中写
# 打开Rerite功能 RewriteEngine On # 如果请求的是真实存在的文件或目录,直接访问 RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # 如果访问的文件或目录不是真事存在,分发请求至 index.php RewriteRule . index.php
无论如何,路由就是如何根据 url 找到你所要访问的类和方法
首先建立目录 /gzy/lib 在 lib 目录里建立 Route.php 类.
conf = new Config(YIN_PATH. '/config/conf.php'); } /** * 路由的分发 */ public function dispatcher() { //echo $_SERVER['REQUEST_URI'];exit; switch ($this->conf->get('url_route')) { //斜杠模式 case 'PATH_INFO' : $request = $this->getRequest("PATH_INFO"); //var_dump($this->parsePathUri($request)); //$this->parsePathUri($request); break; default : $request = $this->getRequest(); break; } return $request; } /** * 获取controller和action */ private function getRequest($pathInfo=""){ if ($pathInfo == "PATH_INFO") { //var_dump($_SERVER); $pathInfo = trim($_SERVER["REQUEST_URI"],"/"); $parm = explode('/',$pathInfo); print_r($parm); if (trim($_SERVER["DOCUMENT_URI"],"/")=="index.php") { $this->modules = isset($parm[1]) ? $parm[1] : $this->conf->get('modules'); $this->controller = isset($parm[2]) ? $parm[2] : $this->conf->get('controller'); $this->action = isset($parm[3]) ? $parm[3] : $this->conf->get('action'); } else { $this->modules = isset($parm[0]) ? $parm[0] : $this->conf->get('modules'); $this->controller = isset($parm[1]) ? $parm[1] : $this->conf->get('controller'); $this->action = isset($parm[2]) ? $parm[2] : $this->conf->get('action'); } //print_r($parm) ;exit; //echo $this->is_url($pathInfo); } else { //var_dump($_SERVER); $this->modules = isset($_GET['g']) ? $_GET['g'] : $this->conf->get('modules'); $this->controller = isset($_GET['c']) ? $_GET['c'] : $this->conf->get('controller'); $this->action = isset($_GET['a']) ? $_GET['a'] : $this->conf->get('action'); } return [ "modules" => $this->modules, "controller" => $this->controller, "action" => $this->action, ]; } /** * @param $request */ public function parsePathUri($request){ }}
马上就要用到模块和控制器了,有了路由(其实本篇完全没具体说路由)根据 url 就能找到控制器了,我们先建立一个模块,然后控制器,然后再接着说如何找到他。
建立目录 /home/controller 然后在 controller 里建立 IndexController.php 类:
在类 gzy 里,我们原来建立了核心入口 run 方法:
pathinfo路径形式 要在conf.php 修改"url_route" => ‘PATH_INFO’, //PATH_INFO 普通模式
路由和配置就讲这么多了。本节结束。
转载地址:http://iscp.baihongyu.com/