本文實例講述了PHP實現的簡單路由和類自動加載功能。分享給大家供大家參考,具體如下:
項目目錄如下
入口文件index.php
<?php define('WEBROOT', 'C:/Users/Administrator/Documents/NetBeansProjects/test'); require_once(WEBROOT.'/core/environment.php'); core__app::run(); //
類自動加載文件environment.php
<?php //根據類名來include文件 class loader { //找到對應文件就include static function load($name) { $file = self::filepath($name); if ($file) { return include $file; } } static function filepath($name, $ext = '.php') { if (!$ext) { $ext = '.php'; } $file = str_replace('__', '/', $name) . $ext; //類名轉路徑 $path .= WEBROOT . '/' . $file; if (file_exists($path)) { return $path; //找到就返回 } return null; } } spl_autoload_register('loader::load');
我這里類的加載規則是 比如core__app::run()
對應 根目錄/core/app.php 的 run()
方法,用到了spl_autoload_register()
函數實現自動加載,當調用某個類名的時候,會自動執行spl_autoload_register('loader::load')
,根據類名include對應的類文件。
app.php入口文件執行的方法開始跑框架流程
<?php class core__app { static function run() { $a = $_SERVER['REQUEST_URI']; $uri = rtrim(preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']), '/'); $params = explode('/', trim($uri, '/')); $count = count($params); if ($count > 1) { $controller = $params[0]; $method = $params[1]; } elseif ($count == 1) { $controller = 'index'; $method = $params[0]; } else { } $filename = WEBROOT . '/controller/' . $controller . '.php'; $controller = 'controller__'.$controller; try { if (!file_exists($filename)) { throw new Exception('controller ' . $controller . ' is not exists!'); return; } include($filename); if (!class_exists($controller)) { throw new Exception('class ' . $controller . ' is not exists'); return; } $obj = new ReflectionClass($controller); if (!$obj->hasMethod($method)) { throw new Exception('method ' . $method . ' is not exists'); return; } } catch (Exception $e) { echo $e; //展示錯誤結果 return; } $newObj = new $controller(); call_user_func_array(array($newObj, $method), $params); } }
根據請求uri去找對應的controller, 用call_user_func_array()
的方式調用controller里的方法
根目錄/controller/test.php
<?php class controller__test { public function write($controller, $method) { //config__test::load('test'); model__test::write($controller, $method); } }
這里其實調用不一定要調用model里的test方法,可以調model目錄下的任意文件,在此之前可以去都讀一些config文件等等操作。
根目錄/model/test.php
<?php class model__test { public function write($model, $method) { echo 'From controller:'.$model.' to model: ' . $model . ' ,method: ' . $method; } }
例如hostname/test/write 這個請求就會從入口文件進來,經過core__app::run
就會找到controller下對應的的controller__test類,執行write()
方法
希望本文所述對大家PHP程序設計有所幫助。