Rumah pembangunan bahagian belakang tutorial 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 ();
?>
Salin selepas log masuk

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

<?php
function __autoload($class_name) {
@require $class_name . '.php';
}
?> 
Salin selepas log masuk

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;

	}

}
?>
Salin selepas log masuk
?

?

<?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;
	}

}
?>
Salin selepas log masuk

?调用方法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);
?>
Salin selepas log masuk

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

AI Hentai Generator

AI Hentai Generator

Menjana ai hentai secara percuma.

Artikel Panas

R.E.P.O. Kristal tenaga dijelaskan dan apa yang mereka lakukan (kristal kuning)
3 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Tetapan grafik terbaik
3 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Cara Memperbaiki Audio Jika anda tidak dapat mendengar sesiapa
3 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Cara Membuka Segala -galanya Di Myrise
4 minggu yang lalu By 尊渡假赌尊渡假赌尊渡假赌

Alat panas

Notepad++7.3.1

Notepad++7.3.1

Editor kod yang mudah digunakan dan percuma

SublimeText3 versi Cina

SublimeText3 versi Cina

Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1

Hantar Studio 13.0.1

Persekitaran pembangunan bersepadu PHP yang berkuasa

Dreamweaver CS6

Dreamweaver CS6

Alat pembangunan web visual

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

Langkah-langkah untuk menetapkan pembolehubah persekitaran PATH bagi sistem Linux Langkah-langkah untuk menetapkan pembolehubah persekitaran PATH bagi sistem Linux Feb 18, 2024 pm 05:40 PM

Cara menetapkan pembolehubah persekitaran PATH dalam sistem Linux Dalam sistem Linux, pembolehubah persekitaran PATH digunakan untuk menentukan laluan di mana sistem mencari fail boleh laku pada baris arahan. Menetapkan pembolehubah persekitaran PATH dengan betul membolehkan kami melaksanakan perintah sistem dan arahan tersuai di mana-mana lokasi. Artikel ini akan memperkenalkan cara untuk menetapkan pembolehubah persekitaran PATH dalam sistem Linux dan memberikan contoh kod terperinci. Lihat pembolehubah persekitaran PATH semasa Jalankan arahan berikut dalam terminal untuk melihat pembolehubah persekitaran PATH semasa: echo$P

2 bulan kemudian, robot humanoid Walker S boleh melipat pakaian 2 bulan kemudian, robot humanoid Walker S boleh melipat pakaian Apr 03, 2024 am 08:01 AM

Editor Laporan Kuasa Mesin: Wu Xin Versi domestik robot humanoid + pasukan model besar menyelesaikan tugas operasi bahan fleksibel yang kompleks seperti melipat pakaian buat kali pertama. Dengan pelancaran Figure01, yang mengintegrasikan model besar berbilang modal OpenAI, kemajuan berkaitan rakan domestik telah menarik perhatian. Baru semalam, UBTECH, "stok robot humanoid nombor satu" China, mengeluarkan demo pertama robot humanoid WalkerS yang disepadukan secara mendalam dengan model besar Baidu Wenxin, menunjukkan beberapa ciri baharu yang menarik. Kini, WalkerS, diberkati oleh keupayaan model besar Baidu Wenxin, kelihatan seperti ini. Seperti Rajah01, WalkerS tidak bergerak, tetapi berdiri di belakang meja untuk menyelesaikan satu siri tugasan. Ia boleh mengikut perintah manusia dan melipat pakaian

Apakah perbezaan antara php include dan include_once Apakah perbezaan antara php include dan include_once Mar 22, 2023 am 10:38 AM

Apabila kami menulis halaman web menggunakan PHP, kadangkala kami perlu memasukkan kod daripada fail PHP lain dalam fail PHP semasa. Pada masa ini, anda boleh menggunakan fungsi include atau include_once untuk melaksanakan kemasukan fail. Jadi, apakah perbezaan antara include dan include_once?

Bagaimana untuk menetapkan pembolehubah persekitaran laluan Bagaimana untuk menetapkan pembolehubah persekitaran laluan Sep 04, 2023 am 11:53 AM

Kaedah untuk menetapkan pembolehubah persekitaran laluan: 1. Sistem Windows, buka "System Properties", klik pilihan "Properties", klik "Advanced System Settings", dalam tetingkap "System Properties", pilih tab "Advanced", dan kemudian klik butang "Environment Variables" ", cari dan klik "Path" untuk mengedit dan menyimpan; 2. Untuk sistem Linux, buka terminal, buka fail konfigurasi bash anda, tambah "export PATH=$PATH: file path" pada penghujung fail dan simpannya; 3. Untuk sistem MacOS, operasi adalah sama seperti di atas.

Peranan dan kepentingan pembolehubah persekitaran PATH dalam Linux Peranan dan kepentingan pembolehubah persekitaran PATH dalam Linux Feb 21, 2024 pm 02:09 PM

"Peranan dan Kepentingan Pembolehubah Persekitaran PATH dalam Linux" Pembolehubah persekitaran PATH ialah salah satu pembolehubah persekitaran yang sangat penting dalam sistem Linux. Ia mentakrifkan direktori di mana sistem mencari program boleh laku. Dalam sistem Linux, apabila pengguna memasukkan arahan dalam terminal, sistem akan mencari satu demi satu dalam direktori yang disenaraikan dalam pembolehubah persekitaran PATH untuk melihat sama ada fail boleh laku perintah itu wujud, ia akan dilaksanakan. Jika tidak, "commandnotfound" akan digesa. Peranan pembolehubah persekitaran PATH: Dipermudahkan

Bagaimana untuk menetapkan pembolehubah persekitaran PATH dengan betul di Linux Bagaimana untuk menetapkan pembolehubah persekitaran PATH dengan betul di Linux Feb 22, 2024 pm 08:57 PM

Cara menetapkan pembolehubah persekitaran PATH dengan betul dalam Linux Dalam sistem pengendalian Linux, pembolehubah persekitaran ialah salah satu mekanisme penting yang digunakan untuk menyimpan maklumat konfigurasi peringkat sistem. Antaranya, pembolehubah persekitaran PATH digunakan untuk menentukan direktori di mana sistem mencari fail boleh laku. Menetapkan pembolehubah persekitaran PATH dengan betul adalah langkah utama untuk memastikan operasi normal sistem. Artikel ini akan memperkenalkan cara menetapkan pembolehubah persekitaran PATH dengan betul dalam Linux dan memberikan contoh kod khusus. 1. Semak pembolehubah persekitaran PATH semasa dan masukkan arahan berikut dalam terminal

Bagaimana untuk mengkonfigurasi pembolehubah persekitaran laluan dalam java Bagaimana untuk mengkonfigurasi pembolehubah persekitaran laluan dalam java Nov 15, 2023 pm 01:20 PM

Langkah-langkah konfigurasi: 1. Cari direktori pemasangan Java; 2. Cari tetapan pembolehubah persekitaran sistem 3. Dalam tetingkap pembolehubah persekitaran, cari pembolehubah bernama "Laluan" dan klik butang edit; tetingkap pembolehubah , klik butang "Baharu", dan masukkan laluan pemasangan Java dalam kotak dialog pop timbul 5. Selepas mengesahkan bahawa input adalah betul, klik butang "OK".

Bagaimana untuk mengkonfigurasi laluan dalam pembolehubah persekitaran java Bagaimana untuk mengkonfigurasi laluan dalam pembolehubah persekitaran java Apr 22, 2023 pm 06:49 PM

1. Cari direktori bin di bawah direktori pemasangan jdk dan salinnya 2. Klik Komputer dan pilih Properties 3. Pilih Advanced, Environment Variables 4. Tampal pada garisan separuh lebar bahasa Inggeris; akhir. Pembolehubah pengguna pentadbir hanya untuk Digunakan oleh pengguna pentadbir, pembolehubah sistem boleh digunakan oleh semua pengguna. Antara pembolehubah persekitaran, laluan digunakan untuk memastikan arahan java dilaksanakan di bawah laluan Ia boleh dikatakan sebagai pautan yang sangat diperlukan dalam konfigurasi pembolehubah persekitaran.

See all articles