目录结构
index.php
<?php //引导请求进入内核 //1、加载core/App.php文件 require_once('/core/App.php');
Home.php
<?php class Home { public function index() { echo "Study PHP!"; } }
App.php
<?php require_once '/core/FrameWork.php'; // 内核的引导文件 //1.内核初始化 $result = FrameWork::init(); $controller = $result['controller']; $action = $result['action']; //加载类文件并实例化控制器 //控制器文件名称和类名称一定要相同 require_once '/application/controller/' . $controller . '.php'; //实例化 // 1.通过直接new //$class = new $controller; //$class-> $action(); //2.通过反射方式 $class = new ReflectionClass($controller); //建立$controller这个类的反射类 $instance = $class->newInstanceArgs(); //相当于实例化$controller类 //访问控制器中的ACTION 可以对方法进行判断。 $method = $class->getmethod($action); $method->invoke($instance);
FrameWork.php
<?php class FrameWork { public static function init() { //拿到请求资源 $request_uri = $_SERVER['REQUEST_URI']; $script_name = $_SERVER['SCRIPT_NAME']; //通过URL解析控制器和ACTION $request = str_replace($script_name, '', $request_uri); $request = ltrim($request, '/'); $request_array = explode('?', $request); $controller_action = $request_array[0]; $controller_action = explode('/', $controller_action); $controller = $controller_action[0]; $action = $controller_action[1]; return array ( 'controller' => $controller, 'action' => $action ); } }