自動加載類文件
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