标题: PHP网页编程之一步步编写PHP的Framework(十二) [打印本页] 作者: 海妖 时间: 2015-2-16 00:22 标题: PHP网页编程之一步步编写PHP的Framework(十二) HTML中的任何元素都要亲自实践,只有明白了什么元素会起到什么效果之后,你才会记忆深刻,而一味的啃书,绝对是不行的,我想大部分新手之所以觉得概念难学,大部分是一个字“懒”,懒是阻止进步的最大敌人,所以克服掉懒的习惯,才能更快的学好一样东西。
我前次在讲redirect和forward的时分我就说过,这两个函数要正常利用还需求修正一下Route这个类,最少要将好比域名,掌握器名,Action名等存储起来,前面挪用redirect,forward的时分可使用。
如今咱们就转到Route.php,本来这个类的代码很复杂:
01 <?php 02 class Route extends Base { 03 public static function run() { 04 $controller= empty($_GET['c']) ? C('defaultController') : trim($_GET['c']); //设置了默许的掌握器 05 $action = empty($_GET['a']) ? C('defaultAction') : trim($_GET['a']); //设置了默许的Action 06 $controllerBasePath = APP_PATH . '/UserApps/Modules/Controllers/'; 07 $controllerFilePath = $controllerBasePath . $controller . 'Controller.php'; 08 if(is_file($controllerFilePath)) { 09 include $controllerFilePath; 10 $controllerName = $controller . 'Controller'; 11 if(class_exists($controllerName)) { 12 $controllerHandler = new $controllerName(); 13 if(method_exists($controllerHandler,$action)) { 14 $controllerHandler->$action(); 15 } else { 16 echo 'the method does not exists'; 17 } 18 } else { 19 echo 'the class does not exists'; 20 } 21 } else { 22 echo 'controller not exists'; 23 } 24 } 25 }
如今咱们需求将域名掏出来,那怎样弄呢?
实践上PHP有一个壮大的超全局变量$_SERVER,良多信息都存储在这外面,咱们可以检查一下:
1 <?php 2 var_dump($_SERVER); 咱们注重到这外面有一个 HTTP_HOST属性,检查PHP手册,这么写的:
Contents of the Host: header from the current request, if there is one. 假定如今有一个URL:http://localhost/test/test.php,那$_SERVER['HTTP_HOST']的值为何呢,实践上为localhost。普通来讲,咱们想取到的是localhost/test,那末怎样获得前面的/test呢?
咱们持续搜刮一下:
发明REQUEST_URI,SCRIPT_FILENAME,SCRIPT_NAME,PHP_SELF的值都为/test/test.php,查询PHP手册注释分离为:
1. The URI which was given in order to access this page; for instance, '/index.html'
2. The absolute pathname of the currently executing script.
3.Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
4. The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.