设为首页 收藏本站
查看: 509|回复: 0

[经验分享] PHP 自动加载对象(以MVC框架为例)

[复制链接]
发表于 2017-4-5 12:19:25 | 显示全部楼层 |阅读模式
<?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 stringThe appServerRootDir. eg: 'C:/Www/phpmvc'
* @param arrayAn array of sub-application paths,<br>
*  eg: $subAppPaths[] = 'WEB-INF/classes/example';, ...
* @param stringThe 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.
*
* @paramstringThe path string
* @paramstringThe path string
* @paramstringThe operating type [optional]
* @public
* @returnsstring
*/
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.
*
* @paramstringThe operating type [optional]
* @protected
* @returnsstring
*/
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 stringThe 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);
?>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-360618-1-1.html 上篇帖子: php 添加水印, 格式转换, 变换大小 Watermark, png2jpg, resize 下篇帖子: 以discuz检测用户名为例分析ajax+php
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表