自动加载类文件
1$_server['request_url']获取域名后置参数
截取处理获取类命和方法名
拼接完成类文件
class_exists() 查看类文件是否存在
method_exists()查看类中的方法是否存在
存在 实例化类 访问方法。
不存在 抛异常
异常类是基类 用的话要实例化下 能够在外边在封装base类 用来报错误信息。php
同事张勇写的自动加载类(参看)this
1.如下类代码为url找对应的类方法url
<?php
class Core
{
private $_controllerName;
private $_actionName;
public function __construct()
{
$this->pareseUrl();
}
public function run()
{
$this->exec();
}
public function exec()
{
if (!(class_exists($this->_controllerName))){
throw new BaseException(ErrorCode::$controller_not_exist);
}
if (!method_exists($this->_controllerName, $this->_actionName)) {
throw new BaseException(ErrorCode::$action_not_exist);
}
$class = new $this->_controllerName;
$action = $this->_actionName;
$class->$action();
}
public function pareseUrl()
{
$requestURI = $_SERVER['REQUEST_URI'];
$queryPos = strpos($requestURI, '?');
if ($queryPos !== false) {
$requestURI = substr($requestURI, 0, $queryPos);
}
$indexPos = strpos($requestURI, "index.php");
if ($indexPos !== false) {
$requestURI = substr($requestURI, $indexPos+strlen("index.php"));
}
$parseStr = trim($requestURI, "/");
if (empty($parseStr)) {
// throw new BaseException(ErrorCode::$request_parameter_missing);
$this->_controllerName = "IndexController";
$this->_actionName = "index";
return;
}
$parseArr = explode("/", $parseStr);
if (count($parseArr)<2) {
throw new BaseException(ErrorCode::$request_parameter_missing);
}
$this->_controllerName = ucfirst($parseArr[0])."Controller";
$this->_actionName = strtolower($parseArr[1]);
}
}
2如下类代码为自动加载类 spa
<?php
class ProjectLoader
{
private $_mapArr;
public static function loadClass($classname)
{
$classpath = self::getClassPath();
if (isset($classpath[$classname])) {
include($classpath[$classname]);
}
}
protected static function getClassPath()
{
static $classpath=array();
if (!empty($classpath)) {
return $classpath;
}
$classpath = self::getClassMapDef();
return $classpath;
}
protected static function getClassMapDef()
{
$lib_path = dirname(__FILE__);
return array(
"BaseController" => $lib_path."/BaseController.php",
"UserController" => $lib_path."/UserController.php",
"TestInfoDao" => $lib_path."/TestInfoDao.php",
);
}
}
spl_autoload_register(array("ProjectLoader","loadClass"));server