`
hudeyong926
  • 浏览: 2028348 次
  • 来自: 武汉
社区版块
存档分类
最新评论

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);
?>
分享到:
评论

相关推荐

    基于PHP面向对象的自定义MVC框架高级项目开发12天视频

    ### 基于PHP面向对象的自定义MVC框架高级项目开发 #### 一、引言 在现代Web开发中,MVC(Model-View-Controller)架构模式因其清晰的结构划分与高度的可维护性而被广泛采用。本系列视频教程旨在通过12天的学习与...

    PHP入门培训教程PHP MVC框架核心类.pdf

    PHP MVC框架核心类教程 PHP MVC框架核心类是PHP入门培训教程中的一部分,该教程旨在帮助初学者快速掌握PHP编程语言并学习MVC框架的核心概念。该教程通过实例演示了框架核心类的设计和实现,帮助学习者快速理解MVC...

    PHP 封装简单MVC框架

    通过这个简单的PHP MVC框架,新手可以逐步掌握Web开发的基本流程和最佳实践,为未来更复杂的项目打下坚实基础。在实际操作中,你可以尝试创建新的模型、控制器和视图,以熟悉整个流程。同时,不要忘记查阅相关文档和...

    简单原生php MVC框架

    【简单原生php MVC框架】是一种轻量级的PHP开发框架,它基于MVC(Model-View-Controller)设计模式,旨在简化Web应用的构建,提高开发效率。MVC模式将应用程序分为三个主要部分:模型(Model)、视图(View)和控制...

    PHPmvc框架项目

    本项目“PHPmvc框架”旨在提供一个自定义的、基于Model-View-Controller(模型-视图-控制器)设计模式的PHP框架,以简化开发流程并提高代码组织性。 首先,我们来详细了解一下MVC模式。MVC是一种软件设计模式,它将...

    php简易MVC框架

    在PHP简易MVC框架中,模型通常包含数据访问对象(DAO)和实体类。DAO负责与数据库交互,执行增删改查操作;实体类则封装了数据结构,保持与数据库表结构的一致性。 **四、视图(View)** 视图文件通常以PHP模板的形式...

    自己写的PHP MVC框架,轻量框架,含bootstrap组件

    总的来说,这个PHP MVC框架为PHP初学者提供了一个学习和实践的平台,不仅可以了解MVC模式的基本原理,还能熟悉数据库操作和前端开发技术。通过深入研究和实践,开发者可以逐渐掌握PHP Web开发的核心技能。

    自己写的PHP MVC框架2.0

    自己写的MVC框架,功能完善,用来写一些小项目是绰绰有余了。实现了MVC三层架构,支持模块化设计,应用目录自动生成,命名空间自动加载到类,url mode,url路由等功能。感兴趣的朋友可以下载回去,一起探讨一起学习...

    自己动手写PHP MVC 框架.

    ### 自己动手写PHP MVC框架 #### 一、引言 在PHP开发领域,MVC(Model-View-Controller)架构模式被广泛采用,它通过将业务逻辑、数据处理与界面展示分离,使得代码结构更加清晰,提高了软件的可维护性和可扩展性...

    PHP傻瓜也能搭建自己框架,手把手搭建一个mvc框架

    https://blog.csdn.net/weixin_39934453/article/details/132242216PHP傻瓜也能搭建自己框架,手把手搭建一个mvc框架PHP最简单自定义自己的框架(一) PHP最简单自定义自己的框架创建目录结构(二) PHP最简单自定义...

    phpMVC框架编程

    ### PHP MVC框架编程详解 随着Web开发技术的不断进步与成熟,PHP开发也逐渐步入了新的阶段,其中最具代表性的发展趋势之一就是采用MVC(Model-View-Controller)框架进行项目构建。MVC架构不仅提高了代码的可读性...

    自己写的PHP MVC框架

    在IT行业中,PHP MVC框架是开发Web应用时常用的一种架构模式。MVC,即Model-View-Controller,是一种设计模式,将应用程序分为三个主要部分,...这样的框架为开发者提供了便利的工具,以构建可扩展、可维护的Web应用。

    php实现基于MVC思想的小框架

    **PHP实现基于MVC思想的小框架** ...通过理解和实践这样的小型PHP MVC框架,开发者能够更好地掌握MVC模式,为后续开发大型项目打下坚实的基础。同时,这个框架也提供了学习和交流的机会,有助于提升PHP编程技能。

    PHP分页类,完美版(可以植入到MVC框架中)

    本文将详细讲解一个名为“PHP分页类,完美版”的工具,它适用于MVC框架,并具备多种分页模式,尤其适合新手学习和使用。 这个分页类的强大之处在于它提供了四种不同的分页模式,可以满足不同场景的需求。默认模式是...

    AMP PHP MVC框架

    AMP-优雅精致的WEB应用开发MVC框架。 为什么选择AMP框架 01) 快速: 框架总大小10余KB,0.0001毫秒迅速载入启动。 02) 高效: 安全高效性能、优越的资源控制模式。 03) 简洁: 单一入口、单一系统加载文件,使用、...

    PHP从零开始打造自己的MVC框架之类的自动加载实现方法详解

    打造MVC框架涉及到很多方面,其中之一便是类的自动加载机制。自动加载是通过指定的规则,在运行时动态加载类文件的一种技术,能够显著提高开发效率,避免手动require或include大量的PHP文件。 根据提供的文件内容,...

    coreMVC框架源代码

    1. **core.php**:这是`coreMVC`框架的核心文件,可能包含了初始化设置、路由解析、类自动加载等功能。在这个文件中,开发者可以找到如何配置和启动框架的入口,以及如何定义和处理URL路由的逻辑。 2. **readme.txt...

    PHP MVC框架中类的自动加载机制实例分析

    在PHP MVC框架中,类的自动加载机制是一个关键特性,它允许开发者在程序运行时按需加载类,而无需显式地使用`require`或`include`语句。这一机制提高了代码的组织性和效率,避免了手动管理大量类文件的麻烦。本实例...

    自己写的MVC框架(PHP)

    这个自编写的PHP MVC框架就是基于这样的设计理念构建的。 首先,MVC架构的核心组成部分: 1. **模型(Model)**:这是应用程序的业务逻辑部分,负责与数据库交互,处理数据。在这个框架中,模型类会封装对数据库的...

    PHP的无框架的MVC开发方案

    在PHP开发中,MVC(Model-View-Controller)架构模式是一种常见的设计模式,它将应用程序分为三个主要组件:模型、视图和控制器,以实现数据处理与展示的分离,提高代码可读性和可维护性。然而,并非所有的项目都...

Global site tag (gtag.js) - Google Analytics