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

简介:
Java代码   收藏代码
  1. <?php  
  2. class autoloader {  
  3.     public static $loader;  
  4.       
  5.     public static function init() {  
  6.         if (self::$loader == NULL)  
  7.             self::$loader = new self ();  
  8.           
  9.         return self::$loader;  
  10.     }  
  11.       
  12.     public function __construct() {  
  13.         spl_autoload_register ( array ($this'model' ) );  
  14.         spl_autoload_register ( array ($this'helper' ) );  
  15.         spl_autoload_register ( array ($this'controller' ) );  
  16.         spl_autoload_register ( array ($this'library' ) );  
  17.     }  
  18.       
  19.     public function library($class) {  
  20.         set_include_path ( get_include_path () . PATH_SEPARATOR . '/lib/' );  
  21.         spl_autoload_extensions ( '.library.php' );  
  22.         spl_autoload ( $class );  
  23.     }  
  24.       
  25.     public function controller($class) {  
  26.         $class = preg_replace ( '/_controller$/ui''', $class );  
  27.           
  28.         set_include_path ( get_include_path () . PATH_SEPARATOR . '/controller/' );  
  29.         spl_autoload_extensions ( '.controller.php' );  
  30.         spl_autoload ( $class );  
  31.     }  
  32.       
  33.     public function model($class) {  
  34.         $class = preg_replace ( '/_model$/ui''', $class );  
  35.           
  36.         set_include_path ( get_include_path () . PATH_SEPARATOR . '/model/' );  
  37.         spl_autoload_extensions ( '.model.php' );  
  38.         spl_autoload ( $class );  
  39.     }  
  40.       
  41.     public function helper($class) {  
  42.         $class = preg_replace ( '/_helper$/ui''', $class );  
  43.           
  44.         set_include_path ( get_include_path () . PATH_SEPARATOR . '/helper/' );  
  45.         spl_autoload_extensions ( '.helper.php' );  
  46.         spl_autoload ( $class );  
  47.     }  
  48.   
  49. }  
  50.   
  51. //call  
  52. autoloader::init ();  
  53. ?>  

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

Java代码   收藏代码
  1. <?php  
  2. function __autoload($class_name) {  
  3. @require $class_name . '.php';  
  4. }  
  5. ?>   

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

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

Classpath.php代码   收藏代码
  1. <?php  
  2. /*  
  3. * $Header: /PHPMVC/phpmvc-base/WEB-INF/classes/phpmvc/utils/ClassPath.php,v 1.4 2006/02/22 07:18:26 who Exp $  
  4. * $Revision: 1.4 $  
  5. * $Date: 2006/02/22 07:18:26 $  
  6. */  
  7. class ClassPath {  
  8.   
  9.     // ----- Depreciated ---------------------------------------------------- //  
  10.   
  11.     /**  
  12.     * <p>Setup the application class paths (PHP 'include_path') for the included  
  13.     * class files, for the duration of the main script</p>  
  14.     *  
  15.     *<p>Returns the class path string for testing purposes  
  16.     *  
  17.     * @depreciated  
  18.     * @param string The appServerRootDir. eg: 'C:/Www/phpmvc'  
  19.     * @param array      An array of sub-application paths,<br>  
  20.     *  eg: $subAppPaths[] = 'WEB-INF/classes/example';, ...  
  21.     * @param string The OS [Optional] [UNIX|WINDOWS|MAC|...] if we have  
  22.     *  trouble detecting the server OS type. Eg: path errors.  
  23.     * @public  
  24.     * @returns string  
  25.     */  
  26.     function setClassPath($appServerRootDir='', $subAppPaths='', $osType='') {  
  27.   
  28.         // Set AppServer root manually for now  
  29.         if($appServerRootDir == '') {  
  30.             echo 'Error: ClassPath :- No php.MVC application root directory specified';  
  31.             exit;  
  32.         }  
  33.   
  34.         #$_ENV; // PHP Superglobals !!  
  35.   
  36.         // Setup the main phpmvc application include() directories here  
  37.         // Note: could be placed in a n xml config file later !!  
  38.         $appDirs = array();  
  39.         $appDirs[] = ''; // application root directory  
  40.         $appDirs[] = 'lib';  
  41.   
  42.         // Add the sub-application paths, if any  
  43.         if(is_array($subAppPaths)) {  
  44.             $appDirs = array_merge($appDirs, $subAppPaths);  
  45.         }  
  46.   
  47.   
  48.         // Setup the platform specific path delimiter character  
  49.         $delim = NULL;  // path delimiter character. (Windows, Unix, Mac!!)  
  50.         $winDir = NULL;  
  51.         if( (int)phpversion() > 4 ) {  
  52.             // PHP 5  
  53.             $winDir = $_ENV["windir"];                  // See: PHP v.4.1.0 Superglobals   
  54.         } else {  
  55.             // PHP 4  
  56.             global $HTTP_ENV_VARS;                      // depreciated-   
  57.             if( array_key_exists("windir", $HTTP_ENV_VARS) ) {  
  58.                 $winDir = $HTTP_ENV_VARS["windir"]; // will be replaced with $_ENV  
  59.             }  
  60.         }  
  61.   
  62.   
  63.         if($osType != '') {  
  64.             if( eregi("WINDOWS", $osType) ) {  
  65.                 $delim = ';';   // Windows  
  66.             } elseif( eregi("UNIX", $osType) ) {  
  67.                 $delim = ':';   // Unix  
  68.             } elseif( eregi("MAC", $osType) ) {  
  69.                 $delim = ':';   // Mac !!!!!  
  70.             }  
  71.         }  
  72.   
  73.         if($delim == NULL) {  
  74.             if( eregi("WIN", $winDir) ) { // _ENV["C:\\Win2K"]  
  75.                 $delim = ';';   // Windows  
  76.             } else {  
  77.                 $delim = ':';   // Unix, Mac !!  
  78.             }  
  79.         }  
  80.   
  81.         // Get the current working directory  
  82.         $path = $appServerRootDir;  
  83.   
  84.         // Strip path directories below 'WEB-INF'  
  85.         $pathToWebInf = ereg_replace("WEB-INF.*$"'', $path);  
  86.   
  87.         // Replace path backslashes with forward slashes  
  88.         // Note: PHP Regular Expressions do not work with backslashes  
  89.         $pathToWebInf = str_replace("\\", "/", $pathToWebInf);  
  90.   
  91.         // Drop the trailing slash, if one is present  
  92.         $pathToWebInf = ereg_replace("/$"'', $pathToWebInf);  
  93.   
  94.         // Setup the environment path string  
  95.         $classPath = NULL;  
  96.         foreach($appDirs as $appDir) {    
  97.             $classPath .= $pathToWebInf.'/'.$appDir.$delim;  
  98.         }  
  99.   
  100.         // Remove trailing delimiter character  
  101.         $classPath = substr($classPath, 0, -1);   
  102.   
  103.         // Setup the include_path for the duration of the main php.MVC script  
  104.         ini_set('include_path', $classPath);  
  105.   
  106.         return $classPath;  // for testing  
  107.   
  108.     }  
  109.   
  110.   
  111.     // ----- Public Methods ------------------------------------------------- //  
  112.   
  113.     function getClassPath($appServerRootDir='', $appDirs, $osType='') {  
  114.   
  115.         // Set AppServer root manually for now  
  116.         if($appServerRootDir == '') {  
  117.             echo 'Error: ClassPath :- No php.MVC application root directory specified';  
  118.             exit;  
  119.         }  
  120.   
  121.         #$_ENV; // PHP Superglobals !!  
  122.   
  123.         // Setup the platform specific path delimiter character  
  124.         $delim = NULL;  // path delimiter character. (Windows, Unix, Mac!!)  
  125.         if($osType == '') {  
  126.             // PHP's build in constant "PATH_SEPARATOR" [unix (:) / win (;)]  
  127.             $delim = PATH_SEPARATOR;  
  128.         } else {  
  129.             // It is handy to be able to specift the OS type for testing  
  130.             $delim = ClassPath::getPathDelimiter($osType);  
  131.         }  
  132.   
  133.         // Get the current working directory  
  134.         $path = $appServerRootDir;  
  135.   
  136.         // Strip path directories below 'WEB-INF'  
  137.         $pathToWebInf = ereg_replace("WEB-INF.*$"'', $path);  
  138.   
  139.         // Replace path backslashes with forward slashes  
  140.         // Note: PHP Regular Expressions do not work with backslashes  
  141.         $pathToWebInf = str_replace("\\", "/", $pathToWebInf);  
  142.   
  143.         // Drop the trailing slash, if one is present  
  144.         $pathToWebInf = ereg_replace("/$"'', $pathToWebInf);  
  145.   
  146.         // Setup the environment path string  
  147.         $classPath      = NULL;  
  148.         $AbsolutePath   = False;    // Say: "/Some/Unix/Path/" or "D:\Some\Win\Path"  
  149.         foreach($appDirs as $appDir) {    
  150.   
  151.             // Check if the specified system path is an absolute path. Absolute system  
  152.             // paths start with a "/" on Unix, and "Ch\:" or "Ch/:" on Win 32.  
  153.             // Eg: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path".  
  154.             $AbsolutePath = ClassPath::absolutePath($appDir);  
  155.   
  156.             if($AbsolutePath == True) {  
  157.                 $classPath .= $appDir.$delim;  
  158.             } else {  
  159.                 $classPath .= $pathToWebInf.'/'.$appDir.$delim;  
  160.             }  
  161.   
  162.         }  
  163.   
  164.         // Remove trailing delimiter character  
  165.         $classPath = substr($classPath, 0, -1);   
  166.   
  167.         return $classPath;  // for testing  
  168.   
  169.     }  
  170.   
  171.   
  172.     /**  
  173.     * Concatenate environment path strings  
  174.     * <p>  
  175.     * Returns the two path strings joined with the correct environment  
  176.     * string delimiter for the host operating system.  
  177.     *   
  178.     * @param        string  The path string  
  179.     * @param        string  The path string  
  180.     * @param        string  The operating type [optional]  
  181.     * @public  
  182.     * @returns  string    
  183.     */  
  184.     function concatPaths($path1, $path2, $osType='') {  
  185.   
  186.         // Setup the platform specific path delimiter character  
  187.         $delim = NULL;  // path delimiter character. (Windows, Unix, Mac!!)  
  188.         $delim = ClassPath::getPathDelimiter($osType);  
  189.   
  190.         $path = $path1 . $delim . $path2;  
  191.         return $path;  
  192.   
  193.     }  
  194.   
  195.   
  196.     // ----- Protected Methods ---------------------------------------------- //  
  197.   
  198.     /**  
  199.     * Get environment path delimiter.  
  200.     * <p>  
  201.     * Returns the environment string delimiter for the host operating system.  
  202.     *  
  203.     * @param        string  The operating type [optional]  
  204.     * @protected  
  205.     * @returns  string    
  206.     */  
  207.     function getPathDelimiter($osType='') {  
  208.   
  209.         // Setup the platform specific path delimiter character  
  210.         $delim = NULL;  // path delimiter character. (Windows, Unix, Mac!!)  
  211.         $winDir = NULL;  
  212.         if( (int)phpversion() > 4 ) {  
  213.             // PHP 5  
  214.             $winDir = $_ENV["windir"];                  // See: PHP v.4.1.0 Superglobals   
  215.         } else {  
  216.             // PHP 4  
  217.             global $HTTP_ENV_VARS;                      // depreciated-   
  218.             if( array_key_exists("windir", $HTTP_ENV_VARS) ) {  
  219.                 $winDir = $HTTP_ENV_VARS["windir"]; // will be replaced with $_ENV  
  220.             }  
  221.         }  
  222.   
  223.         if($osType != '') {  
  224.             if( eregi("WINDOWS", $osType) ) {  
  225.                 $delim = ';';   // Windows  
  226.             } elseif( eregi("UNIX", $osType) ) {  
  227.                 $delim = ':';   // Unix  
  228.             } elseif( eregi("MAC", $osType) ) {  
  229.                 $delim = ':';   // Mac !!!!!  
  230.             }  
  231.         }  
  232.   
  233.         if($delim == NULL) {  
  234.             if( eregi("WIN", $winDir) ) { // _ENV["C:\\Win2K"]  
  235.                 $delim = ';';   // Windows  
  236.             } else {  
  237.                 $delim = ':';   // Unix, Mac !!  
  238.             }  
  239.         }  
  240.   
  241.         return $delim;  
  242.   
  243.     }  
  244.   
  245.   
  246.     /**   
  247.     * Check if the specified system path is an absolute path. Absolute system  
  248.     * paths start with a "/" on Unix, and "Ch\:" or "Ch/:" on Win 32.  
  249.     * Eg: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path".  
  250.     *  
  251.     * Returns True if the suppplied path absolute, otherwise returns False  
  252.     *  
  253.     * @param string The path to check, like: "/Some/Unix/Path/" or  
  254.     *                       "D:\Some\Win\Path".  
  255.     * @public  
  256.     * @returns boolean  
  257.     */  
  258.     function absolutePath($systemPath) {  
  259.   
  260.         // Say: "/Some/Unix/Path/" or "D:\Some\Win\Path" or "D:/Some/Win/Path"  
  261.         $fAbsolutePath  = False;        // Boolean flag value  
  262.   
  263.         //"[/]Some/Unix/Path/"  
  264.         if (preg_match("/^\//", $systemPath)) {  
  265.             $fAbsolutePath = True;  
  266.         //"[D:\]Some\Win\Path"  
  267.         // "i" says "ignore case"  
  268.         // Note the extra escape "\" reqd for this to work with  PHP !!!  
  269.         } elseif(preg_match("/^[a-z]:\\\/i", $systemPath)) {      
  270.             $fAbsolutePath = True;  
  271.         //"[D:/]Some/Win/Path"  
  272.         } elseif(preg_match("/^[a-z]:\//i", $systemPath)) {  
  273.             $fAbsolutePath = True;  
  274.         }  
  275.   
  276.         return $fAbsolutePath;  
  277.   
  278.     }  
  279.   
  280. }  
  281. ?>  
 

 

Modulepaths.php代码   收藏代码
  1. <?php  
  2. /*  
  3. * $Header: oohforms/WEB-INF/ModulePaths.php  
  4. * $Revision:  
  5. * $Date: 2003.04.22  
  6. *  
  7. * ====================================================================  
  8. * The module paths  
  9. *  
  10. * @author John C Wildenauer  
  11. * @version  
  12. * @public  
  13. */  
  14. class ModulePaths {  
  15.   
  16.     /**  
  17.     * Return an array of global paths  
  18.     *  
  19.     * @public  
  20.     * @returns array  
  21.     */  
  22.     function getModulePaths() {  
  23.   
  24.         // Setup the main module include() directories here  
  25.         // Note: could be placed in an xml config file later !!  
  26.         $appDirs    = array();  
  27.         $appDirs[]  = ''; // starting with the sub-application home directory  
  28.   
  29.         $appDirs[]  = 'login';  
  30.         $appDirs[]  = 'login/classes';  
  31.         $appDirs[]  = 'login/tpl';  
  32.   
  33.         $appDirs[]  = 'project';  
  34.         $appDirs[]  = 'project/classes';  
  35.         $appDirs[]  = 'project/tpl';  
  36.   
  37.         return $appDirs;  
  38.     }  
  39.   
  40. }  
  41. ?>  

 调用方法autoloader.php

Java代码   收藏代码
  1. <?php  
  2. // Set the application path  
  3. $moduleRootDir = 'D:/workspace/eh_plat_wms/dev_src';    // no trailing slash  
  4.   
  5. // Set the OS Type [Optional] [UNIX|WINDOWS|MAC] if we have  
  6. // trouble detecting the server OS type. Eg: path errors.  
  7. $osType = 'WINDOWS';  
  8.   
  9. // Setup application class paths first  
  10. include 'lib/ClassPath.php';  
  11.   
  12. // Setup the module paths  
  13. include 'config/ModulePaths.php';  
  14. $modulePaths = ModulePaths::getModulePaths();  
  15. $mPath = ClassPath::getClassPath($moduleRootDir,$modulePaths, $osType);  
  16.   
  17. // Retrieve and merge the php.ini path settings  
  18. $iniPath = ini_get('include_path');  
  19. $cPath = ClassPath::concatPaths($mPath, $iniPath, $osType);  
  20. echo $cPath;  
  21. // And set the 'include_path' variables, as used by the file functions  
  22. ini_set('include_path', $cPath);  
  23. ?>  
相关文章
|
15天前
|
PHP 项目管理 开发者
深入解析PHP的命名空间和自动加载机制
【4月更文挑战第4天】 在PHP的编程世界中,命名空间和自动加载机制是构建大型应用程序时不可或缺的工具。本文将深入探讨这两个概念,揭示它们如何简化代码结构、避免类名冲突以及提高代码维护性。通过对PHP命名空间的由来、作用域和使用方法的细致剖析,以及对自动加载机制工作原理和应用实践的全面讲解,读者将获得有效管理复杂项目中依赖关系的能力。
|
17天前
|
缓存 PHP 开发者
PHP中的自动加载机制及其优化方法
传统的PHP开发中,经常会遇到类文件加载繁琐、效率低下的情况,而PHP的自动加载机制能够很好地解决这一问题。本文将深入探讨PHP中的自动加载机制,介绍其原理及实现方式,并提出了一些优化方法,帮助开发者提升代码加载效率,提高应用性能。
|
21天前
|
PHP 数据库 开发者
深入理解PHP中的命名空间与自动加载机制
在PHP开发实践中,合理利用命名空间和自动加载机制能够显著提升代码的可维护性和效率。本文将详细探讨PHP命名空间的概念、作用以及如何结合自动加载机制来优化代码结构。通过实例分析,我们将了解如何避免常见的命名冲突问题,并掌握自动加载策略在项目中的实际应用。文章的目的是为读者提供一套清晰的指南,帮助其在实际项目中灵活运用这些关键技术,以实现更加模块化和高效的代码管理。
|
30天前
|
PHP 开发者
深入理解PHP的命名空间与自动加载机制
【2月更文挑战第29天】在现代PHP开发实践中,命名空间和自动加载机制是提升代码组织和维护效率的重要概念。本文首先介绍命名空间的基本概念及其在PHP中的应用,然后详细探讨了自动加载机制的原理与实现,并通过示例展示了如何在实际项目中合理运用这些特性来优化代码结构,减少冗余,并提高模块间的解耦性。
|
24天前
|
PHP
深入理解PHP的命名空间与自动加载机制
在现代PHP开发中,命名空间和自动加载机制是两个重要的特性,它们有助于解决代码重用、依赖管理等问题。本文将详细介绍PHP的命名空间概念、如何定义和使用命名空间,以及自动加载机制的原理和实现方法。通过阅读本文,你将更好地理解这些特性,并能够在实际项目中灵活运用。
|
1月前
|
PHP
深入理解PHP的命名空间和自动加载机制
【2月更文挑战第21天】在PHP开发中,命名空间和自动加载机制是两个非常重要的概念。本文将深入探讨这两个概念,解释它们的作用,以及如何在项目中使用它们来提高代码的可维护性和可读性。文章将通过实例代码,详细解析命名空间的使用规则和自动加载机制的工作原理,帮助读者更好地理解和应用这两个特性。
15 0
|
29天前
|
PHP 开发者
深入理解PHP的命名空间与自动加载机制
【2月更文挑战第30天】在现代PHP开发中,命名空间和自动加载机制是两个重要的特性,它们为代码的组织和重用提供了强大的支持。本文将深入探讨PHP中的命名空间概念,并详细解析自动加载机制的原理及其实现方法。通过阅读本文,读者可以掌握如何有效地使用命名空间来避免名称冲突,以及如何利用自动加载机制提高代码的可维护性和性能。
|
29天前
|
PHP 开发者
深入理解PHP的命名空间与自动加载机制
【2月更文挑战第30天】在PHP的编程实践中,命名空间和自动加载机制是实现代码组织和维护的重要工具。本文将探讨命名空间的概念、如何合理地使用它们来避免名称冲突,并深入解析自动加载机制的原理及其在现代PHP框架中的应用。通过理解这些核心概念,开发者可以编写出更加模块化、易于维护的PHP代码。
|
3天前
|
PHP 开发者
深入理解PHP中的命名空间与自动加载机制
【4月更文挑战第16天】在PHP的编程实践中,命名空间和自动加载机制是两个核心概念,它们不仅提高了代码的可维护性,还增强了代码的复用性。本文将详细探讨PHP中命名空间的概念、实现及其与自动加载机制的结合使用,帮助开发者构建更加模块化和易于管理的PHP应用程序。通过实例分析,我们将了解如何有效地利用这些特性来优化项目结构,减少代码冗余,并避免潜在的命名冲突。
9 4
|
16天前
|
前端开发 安全 Java
使用Java Web框架:Spring MVC的全面指南
【4月更文挑战第3天】Spring MVC是Spring框架的一部分,用于构建高效、模块化的Web应用。它基于MVC模式,支持多种视图技术。核心概念包括DispatcherServlet(前端控制器)、HandlerMapping(请求映射)、Controller(处理请求)、ViewResolver(视图解析)和ModelAndView(模型和视图容器)。开发流程涉及配置DispatcherServlet、定义Controller、创建View、处理数据、绑定模型和异常处理。
使用Java Web框架:Spring MVC的全面指南