首頁 後端開發 php教程 PHP 自动加载对象(以MVC框架替例)

PHP 自动加载对象(以MVC框架替例)

Jun 13, 2016 pm 12:33 PM
include path the

PHP 自动加载对象(以MVC框架为例)

<?php
class autoloader {
	public static $loader;
	
	public static function init() {
		if (self::$loader == NULL)
			self::$loader = new self ();
		
		return self::$loader;
	}
	
	public function __construct() {
		spl_autoload_register ( array ($this, 'model' ) );
		spl_autoload_register ( array ($this, 'helper' ) );
		spl_autoload_register ( array ($this, 'controller' ) );
		spl_autoload_register ( array ($this, 'library' ) );
	}
	
	public function library($class) {
		set_include_path ( get_include_path () . PATH_SEPARATOR . '/lib/' );
		spl_autoload_extensions ( '.library.php' );
		spl_autoload ( $class );
	}
	
	public function controller($class) {
		$class = preg_replace ( '/_controller$/ui', '', $class );
		
		set_include_path ( get_include_path () . PATH_SEPARATOR . '/controller/' );
		spl_autoload_extensions ( '.controller.php' );
		spl_autoload ( $class );
	}
	
	public function model($class) {
		$class = preg_replace ( '/_model$/ui', '', $class );
		
		set_include_path ( get_include_path () . PATH_SEPARATOR . '/model/' );
		spl_autoload_extensions ( '.model.php' );
		spl_autoload ( $class );
	}
	
	public function helper($class) {
		$class = preg_replace ( '/_helper$/ui', '', $class );
		
		set_include_path ( get_include_path () . PATH_SEPARATOR . '/helper/' );
		spl_autoload_extensions ( '.helper.php' );
		spl_autoload ( $class );
	}

}

//call
autoloader::init ();
?>
登入後複製

1, 在程序使用未声明的类时会自动调用 __autolaod() 函数来加载;

<?php
function __autoload($class_name) {
@require $class_name . '.php';
}
?> 
登入後複製

2.其中 spl_autoload_register() 用来注册一个自动调用的函数, 可以注册多个函数!

3.$iniPath = ini_get('include_path');ini_set('include_path', $iniPath. . $cPath);通过设置环境变量来达到autoload目的,设置包含路径,以后可以直接包含这些目录中的文件,不需要再写详细的路径了。方法三取自php.MVC,使用参照php.MVC文档

<?php
/*
* $Header: /PHPMVC/phpmvc-base/WEB-INF/classes/phpmvc/utils/ClassPath.php,v 1.4 2006/02/22 07:18:26 who Exp $
* $Revision: 1.4 $
* $Date: 2006/02/22 07:18:26 $
*/
class ClassPath {

	// ----- Depreciated ---------------------------------------------------- //

	/**
	* <p>Setup the application class paths (PHP 'include_path') for the included
	* class files, for the duration of the main script</p>
	*
	*<p>Returns the class path string for testing purposes
	*
	* @depreciated
	* @param string	The appServerRootDir. eg: 'C:/Www/phpmvc'
	* @param array		An array of sub-application paths,<br>
	*  eg: $subAppPaths[] = 'WEB-INF/classes/example';, ...
	* @param string	The OS [Optional] [UNIX|WINDOWS|MAC|...] if we have
	*  trouble detecting the server OS type. Eg: path errors.
	* @public
	* @returns string
	*/
	function setClassPath($appServerRootDir='', $subAppPaths='', $osType='') {

		// Set AppServer root manually for now
		if($appServerRootDir == '') {
			echo 'Error: ClassPath :- No php.MVC application root directory specified';
			exit;
		}

		#$_ENV;	// PHP Superglobals !!

		// Setup the main phpmvc application include() directories here
		// Note: could be placed in a n xml config file later !!
		$appDirs = array();
		$appDirs[] = ''; // application root directory
		$appDirs[] = 'lib';

		// Add the sub-application paths, if any
		if(is_array($subAppPaths)) {
			$appDirs = array_merge($appDirs, $subAppPaths);
		}


		// Setup the platform specific path delimiter character
		$delim = NULL;	// path delimiter character. (Windows, Unix, Mac!!)
		$winDir = NULL;
		if( (int)phpversion() > 4 ) {
			// PHP 5
			$winDir = $_ENV["windir"];					// See: PHP v.4.1.0 Superglobals 
		} else {
			// PHP 4
			global $HTTP_ENV_VARS;						// depreciated- 
			if( array_key_exists("windir", $HTTP_ENV_VARS) ) {
				$winDir = $HTTP_ENV_VARS["windir"];	// will be replaced with $_ENV
			}
		}


		if($osType != '') {
			if( eregi("WINDOWS", $osType) ) {
				$delim = ';';	// Windows
			} elseif( eregi("UNIX", $osType) ) {
				$delim = ':';	// Unix
			} elseif( eregi("MAC", $osType) ) {
				$delim = ':';	// Mac !!!!!
			}
		}

		if($delim == NULL) {
			if( eregi("WIN", $winDir) ) { // _ENV["C:\\Win2K"]
			    $delim = ';';	// Windows
			} else {
				$delim = ':';	// Unix, Mac !!
			}
		}

		// Get the current working directory
		$path = $appServerRootDir;

		// Strip path directories below 'WEB-INF'
		$pathToWebInf = ereg_replace("WEB-INF.*$", '', $path);

		// Replace path backslashes with forward slashes
		// Note: PHP Regular Expressions do not work with backslashes
		$pathToWebInf = str_replace("\\", "/", $pathToWebInf);

		// Drop the trailing slash, if one is present
		$pathToWebInf = ereg_replace("/$", '', $pathToWebInf);

		// Setup the environment path string
		$classPath = NULL;
		foreach($appDirs as $appDir) {	
			$classPath .= $pathToWebInf.'/'.$appDir.$delim;
		}

		// Remove trailing delimiter character
		$classPath = substr($classPath, 0, -1);	

		// Setup the include_path for the duration of the main php.MVC script
		ini_set('include_path', $classPath);

		return $classPath;	// for testing

	}


	// ----- Public Methods ------------------------------------------------- //

	function getClassPath($appServerRootDir='', $appDirs, $osType='') {

		// Set AppServer root manually for now
		if($appServerRootDir == '') {
			echo 'Error: ClassPath :- No php.MVC application root directory specified';
			exit;
		}

		#$_ENV;	// PHP Superglobals !!

		// Setup the platform specific path delimiter character
		$delim = NULL;	// path delimiter character. (Windows, Unix, Mac!!)
		if($osType == '') {
			// PHP's build in constant "PATH_SEPARATOR" [unix (:) / win (;)]
			$delim = PATH_SEPARATOR;
		} else {
			// It is handy to be able to specift the OS type for testing
			$delim = ClassPath::getPathDelimiter($osType);
		}

		// Get the current working directory
		$path = $appServerRootDir;

		// Strip path directories below 'WEB-INF'
		$pathToWebInf = ereg_replace("WEB-INF.*$", '', $path);

		// Replace path backslashes with forward slashes
		// Note: PHP Regular Expressions do not work with backslashes
		$pathToWebInf = str_replace("\\", "/", $pathToWebInf);

		// Drop the trailing slash, if one is present
		$pathToWebInf = ereg_replace("/$", '', $pathToWebInf);

		// Setup the environment path string
		$classPath		= NULL;
		$AbsolutePath	= False;	// Say: "/Some/Unix/Path/" or "D:\Some\Win\Path"
		foreach($appDirs as $appDir) {	

			// Check if the specified system path is an absolute path. Absolute system
			// paths start with a "/" on Unix, and "Ch\:" or "Ch/:" on Win 32.
			// Eg: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path".
			$AbsolutePath = ClassPath::absolutePath($appDir);

			if($AbsolutePath == True) {
				$classPath .= $appDir.$delim;
			} else {
				$classPath .= $pathToWebInf.'/'.$appDir.$delim;
			}

		}

		// Remove trailing delimiter character
		$classPath = substr($classPath, 0, -1);	

		return $classPath;	// for testing

	}


	/**
	* Concatenate environment path strings
	* <p>
	* Returns the two path strings joined with the correct environment
	* string delimiter for the host operating system.
	* 
	* @param		string	The path string
	* @param		string	The path string
	* @param		string	The operating type [optional]
	* @public
	* @returns	string	
	*/
	function concatPaths($path1, $path2, $osType='') {

		// Setup the platform specific path delimiter character
		$delim = NULL;	// path delimiter character. (Windows, Unix, Mac!!)
		$delim = ClassPath::getPathDelimiter($osType);

		$path = $path1 . $delim . $path2;
		return $path;

	}


	// ----- Protected Methods ---------------------------------------------- //

	/**
	* Get environment path delimiter.
	* <p>
	* Returns the environment string delimiter for the host operating system.
	*
	* @param		string	The operating type [optional]
	* @protected
	* @returns	string	
	*/
	function getPathDelimiter($osType='') {

		// Setup the platform specific path delimiter character
		$delim = NULL;	// path delimiter character. (Windows, Unix, Mac!!)
		$winDir = NULL;
		if( (int)phpversion() > 4 ) {
			// PHP 5
			$winDir = $_ENV["windir"];					// See: PHP v.4.1.0 Superglobals 
		} else {
			// PHP 4
			global $HTTP_ENV_VARS;						// depreciated- 
			if( array_key_exists("windir", $HTTP_ENV_VARS) ) {
				$winDir = $HTTP_ENV_VARS["windir"];	// will be replaced with $_ENV
			}
		}

		if($osType != '') {
			if( eregi("WINDOWS", $osType) ) {
				$delim = ';';	// Windows
			} elseif( eregi("UNIX", $osType) ) {
				$delim = ':';	// Unix
			} elseif( eregi("MAC", $osType) ) {
				$delim = ':';	// Mac !!!!!
			}
		}

		if($delim == NULL) {
			if( eregi("WIN", $winDir) ) { // _ENV["C:\\Win2K"]
			    $delim = ';';	// Windows
			} else {
				$delim = ':';	// Unix, Mac !!
			}
		}

		return $delim;

	}


	/** 
	* Check if the specified system path is an absolute path. Absolute system
	* paths start with a "/" on Unix, and "Ch\:" or "Ch/:" on Win 32.
	* Eg: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path".
	*
	* Returns True if the suppplied path absolute, otherwise returns False
	*
	* @param string	The path to check, like: "/Some/Unix/Path/" or
	*						"D:\Some\Win\Path".
	* @public
	* @returns boolean
	*/
	function absolutePath($systemPath) {

		// Say: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path"
		$fAbsolutePath	= False;		// Boolean flag value

		//"[/]Some/Unix/Path/"
		if (preg_match("/^\//", $systemPath)) {
			$fAbsolutePath = True;
		//"[D:\]Some\Win\Path"
		// "i" says "ignore case"
		// Note the extra escape "\" reqd for this to work with  PHP !!!
		} elseif(preg_match("/^[a-z]:\\\/i", $systemPath)) {	
			$fAbsolutePath = True;
		//"[D:/]Some/Win/Path"
		} elseif(preg_match("/^[a-z]:\//i", $systemPath)) {
			$fAbsolutePath = True;
		}

		return $fAbsolutePath;

	}

}
?>
登入後複製
?

?

<?php
/*
* $Header: oohforms/WEB-INF/ModulePaths.php
* $Revision:
* $Date: 2003.04.22
*
* ====================================================================
* The module paths
*
* @author John C Wildenauer
* @version
* @public
*/
class ModulePaths {

	/**
	* Return an array of global paths
	*
	* @public
	* @returns array
	*/
	function getModulePaths() {

		// Setup the main module include() directories here
		// Note: could be placed in an xml config file later !!
		$appDirs	= array();
		$appDirs[]	= ''; // starting with the sub-application home directory

		$appDirs[]	= 'login';
		$appDirs[]	= 'login/classes';
		$appDirs[]	= 'login/tpl';

		$appDirs[]	= 'project';
		$appDirs[]	= 'project/classes';
		$appDirs[]	= 'project/tpl';

		return $appDirs;
	}

}
?>
登入後複製

?调用方法autoloader.php

<?php
// Set the application path
$moduleRootDir = 'D:/workspace/eh_plat_wms/dev_src';	// no trailing slash

// Set the OS Type [Optional] [UNIX|WINDOWS|MAC] if we have
// trouble detecting the server OS type. Eg: path errors.
$osType = 'WINDOWS';

// Setup application class paths first
include 'lib/ClassPath.php';

// Setup the module paths
include 'config/ModulePaths.php';
$modulePaths = ModulePaths::getModulePaths();
$mPath = ClassPath::getClassPath($moduleRootDir,$modulePaths, $osType);

// Retrieve and merge the php.ini path settings
$iniPath = ini_get('include_path');
$cPath = ClassPath::concatPaths($mPath, $iniPath, $osType);
echo $cPath;
// And set the 'include_path' variables, as used by the file functions
ini_set('include_path', $cPath);
?>
登入後複製

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

設定Linux系統的PATH環境變數步驟 設定Linux系統的PATH環境變數步驟 Feb 18, 2024 pm 05:40 PM

Linux系統如何設定PATH環境變數在Linux系統中,PATH環境變數用來指定係統在命令列中搜尋執行檔的路徑。正確設定PATH環境變數可以方便我們在任何位置執行系統指令和自訂指令。本文將介紹如何在Linux系統中設定PATH環境變量,並提供詳細的程式碼範例。查看目前的PATH環境變數在終端機中執行以下指令,可以查看目前的PATH環境變數:echo$P

2 個月不見,人形機器人 Walker S 會摺衣服了 2 個月不見,人形機器人 Walker S 會摺衣服了 Apr 03, 2024 am 08:01 AM

機器之能報道編輯:吳昕國內版的人形機器人+大模型組隊,首次完成疊衣服這類複雜柔性材料的操作任務。隨著融合了OpenAI多模態大模型的Figure01揭開神秘面紗,國內同行的相關進展一直備受關注。就在昨天,國內"人形機器人第一股"優必選發布了人形機器人WalkerS深入融合百度文心大模型後的首個Demo,展示了一些有趣的新功能。現在,得到百度文心大模型能力加持的WalkerS是這個樣子的。和Figure01一樣,WalkerS沒有走動,而是站在桌子後面完成一系列任務。它可以聽從人類的命令,折疊衣物

php include和include_once有什麼差別 php include和include_once有什麼差別 Mar 22, 2023 am 10:38 AM

當我們在使用 PHP 編寫網頁時,有時我們需要在目前 PHP 檔案中包含其他 PHP 檔案中的程式碼。這時,就可以使用 include 或 include_once 函數來實作檔案包含。那麼,include 和 include_once 到底有什麼差別呢?

如何設定path環境變數 如何設定path環境變數 Sep 04, 2023 am 11:53 AM

設定path環境變數的方法:1、Windows系統,開啟“系統屬性”,點選“屬性”選項,點選“進階系統設定”,在“系統屬性”視窗中,選擇“進階”標籤,然後點選“環境變量」按鈕,找到並點擊「Path」編輯儲存後即可;2、Linux系統,打開終端,打開你的bash配置文件,在文件末尾添加「export PATH=$PATH:文件路徑」保存即可;3、 MacOS系統,操作同上。

Linux中PATH環境變數的作用與重要性 Linux中PATH環境變數的作用與重要性 Feb 21, 2024 pm 02:09 PM

《Linux中PATH環境變數的作用與重要性》PATH環境變數是Linux系統中非常重要的環境變數之一,它定義了系統在哪些目錄中尋找可執行程式。在Linux系統中,當使用者在終端輸入一個命令時,系統會在PATH環境變數所列出的目錄中逐個查找是否存在該命令的可執行文件,如果找到則執行,否則會提示「commandnotfound」。 PATH環境變數的作用:簡化

如何正確設定Linux中的PATH環境變數 如何正確設定Linux中的PATH環境變數 Feb 22, 2024 pm 08:57 PM

如何正確設定Linux中的PATH環境變數在Linux作業系統中,環境變數是用來儲存系統層級的設定資訊的重要機制之一。其中,PATH環境變數被用來指定係統在哪些目錄中尋找可執行檔。正確設定PATH環境變數是確保系統正常運作的關鍵步驟。本文將介紹如何正確設定Linux中的PATH環境變量,並提供具體的程式碼範例。 1.查看目前PATH環境變數在終端機中輸入以下命

java中如何配置path環境變數 java中如何配置path環境變數 Nov 15, 2023 pm 01:20 PM

設定步驟:1、找到Java安裝目錄;2、找到系統的環境變數設定;3、在環境變數視窗中,找到名為「Path」的變量,並點擊編輯按鈕;4、在彈出的編輯環境變數窗口中,點選「新建」按鈕,並在彈出的對話框中輸入Java的安裝路徑;5、確認輸入正確後,點選「確定」按鈕即可。

java環境變數怎麼配置path java環境變數怎麼配置path Apr 22, 2023 pm 06:49 PM

1、找到jdk安裝目錄下的bin目錄進行複製2、點選計算機,選擇屬性;3、選擇高級,環境變數;4、path行處進行貼上,注意末尾用英文半角符號(;)administrater用戶變數只針對administrater使用者使用,系統變數所有的使用者都可以使用。在環境變數中,path是用來保證java指令在路徑下執行的,可以說是環境變數配置中不可或缺的環節。

See all articles