recherche
Maisondéveloppement back-endtutoriel php PHP 自动加载对象(以MVC框架替例)

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);
?>
Déclaration
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
设置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 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、确认输入正确后,点击“确定”按钮即可。

Linux中PATH环境变量的作用和重要性Linux中PATH环境变量的作用和重要性Feb 21, 2024 pm 02:09 PM

《Linux中PATH环境变量的作用和重要性》PATH环境变量是Linux系统中非常重要的环境变量之一,它定义了系统在哪些目录中寻找可执行程序。在Linux系统中,当用户在终端输入一个命令时,系统会在PATH环境变量所列出的目录中逐个查找是否存在该命令的可执行文件,如果找到则执行,否则会提示“commandnotfound”。PATH环境变量的作用:简化

java环境变量怎么配置pathjava环境变量怎么配置pathApr 22, 2023 pm 06:49 PM

1、找到jdk安装目录下的bin目录进行复制2、点击计算机,选择属性;3、选择高级,环境变量;4、path行处进行粘贴,注意末尾用英文半角符号(;)administrater用户变量只针对administrater用户使用,系统变量所有的用户都可以使用。在环境变量中,path是用来保证java命令在路径下执行的,可以说是环境变量配置中不可缺少的环节。

See all articles

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
4 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semainesBy尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Version Mac de WebStorm

Version Mac de WebStorm

Outils de développement JavaScript utiles

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Navigateur d'examen sécurisé

Navigateur d'examen sécurisé

Safe Exam Browser est un environnement de navigation sécurisé permettant de passer des examens en ligne en toute sécurité. Ce logiciel transforme n'importe quel ordinateur en poste de travail sécurisé. Il contrôle l'accès à n'importe quel utilitaire et empêche les étudiants d'utiliser des ressources non autorisées.

Dreamweaver Mac

Dreamweaver Mac

Outils de développement Web visuel