自己动手写个小框架之七

     框架需要路由访问以index.php为起始点,自然需要一些对路由地址的重写限制。在根目录下写一个.htaccess文件,作为框架的路由访问限制,配合router类达到路由地址格式的统一。而.htaccess文件还需要web服务器的配合,如果使用的是apache则配置如下。

     我们先来看看.htaccess的内容:

RewriteEngine on
RewriteRule !\.(js|gif|jpg|png|css)$ index.php

内容很直观,先打开路由重写,然后是重写规则,非那些指定格式的地址则跳到index.php。

     接着对apache进行一些配置,以支持重写规则。配置前先在phpinfo里检查apache2handler里有没有mod_rewite。如图:

如果没有则说明没加载重写模块,需打开apache的配置文件httpd.conf找到LoadModule rewrite_module modules/mod_rewrite.so 去掉前面的#即可,然后在空白处添加 AccessFileName .htaccess 以识别.htaccess文件。重启apache服务器查看phpinfo是否有mod_rewrite,出现了那么可以进行下一步配置。

     在httpd.conf文件中,查找

<Directory />
Options FollowSymLinks
AllowOverride None

把None改为All就行了。

如果在配置apache时自己指定了htdocs的位置而非默认位置则查找<Directory "你指定htdocs的位置">。例如我机子上要找到

<Directory "C:/Program Files/htdocs">  这里"C:/Program Files/htdocs" 是我指定的htdocs的位置,然后把其内容

Options Indexes FollowSymLinks 修改为

Options FollowSymLinks ;把AllowOverride None 修改为AllowOverride All。重启apache服务器就好了。

运行结果:

1)地址直接不走index.php 在浏览器中输入http://localhost/dluf/kernel/ 会发生什么

2)地址格式正常情况下 在浏览器中输入http://localhost/dluf/index.php/default/index/dluf 会发生什么

我们再回顾下“自己动手写个小框架之二”中的内容,index.php 及index中调用的router对象:

index.php 调用路由解析$router->loadTpl()

 1 <?php
 2 
 3 require_once (__DIR__ . '\startup.php');
 4 $app_path = str_replace($_SERVER['DOCUMENT_ROOT'], "", __FILE__);
 5 $se_string = str_replace($app_path, "", $_SERVER['REQUEST_URI']);
 6 $register = new Register();
 7 $loader = new Loader($register);
 8 $router = new router($se_string, $loader);
 9 //echo print_r($router, true);
10 //exit();
11 try {
12     $router->loadTpl();
13 } catch (Exception $exception) {
14     echo "INFO:" . $exception;
15 }
16 ?>

router对象的loadTpl()函数

 1 public function loadTpl() {
 2         if($this->urltag != "default"){
 3             $this->loader->register('controller', $this->classname);
 4             $re = new ReflectionClass($this->classname . "Controller");
 5             $controller = $re->newInstance();
 6 //            echo print_r($this->urlarr,TRUE);
 7             if(isset($this->method)){
 8                 $method = $re->getMethod($this->method);
 9             }else{
10                 $method = $re->getMethod("indexAction");
11             }
12            $method->invoke($controller, $this->argsarr);
13         }else{
14             echo "welcome use this system!";
15         }
16         
17     }

从测试一的显示 “welcome use this system!” 可以看出,写不符合规则的地址,将会被转到index.php,跑index.php的逻辑。

      至此,“自己动手写个小框架系列“告一段落,当然还有许多地方可以丰富,比如封装doctrine使框架实现orm完善框架的数据层,还可以在控制层基类中增加日志功能,方便跟踪调试。这里仅就一些基本的东西进行实现,但在写小框架的过程中我们能想一下其他成熟框架的实现方法,相信也会有些收获。

  

原文地址:https://www.cnblogs.com/dluf/p/3048282.html