search
HomeBackend DevelopmentPHP Tutorialphp class automatic loading

rare has a built-in class automatic loading function. When using a class, it can be used directly without requiring (include) the class file.

This type of automatic loading function is very independent. If you need it, you can use it directly in other frameworks (any PHP program).

1. First introduce rareAutoLoad.class.php

2.Registration function

  1. /**
  2. * Class autoloading
  3. * http://raremvc.googlecode.com
  4. * http://rare.hongtao3.com
  5. * @example
  6. * include 'rareAutoLoad.php';
  7. * $option=array('dirs' =>'/www/lib/share/,/www/lib/api/',//class Search from those directories
  8. * 'cache'=>'/tmp/111111.php',//class path Cache file
  9. * 'suffix'=>'.class.php' //The suffix of the PHP class file that requires automatic class loading
  10. * "hand"=>true, //Whether to manually update the class path file, when it is false The cache file is written to the specified cache file,
  11. * //If true, you need to manually allow the autoLoad.php file
  12. * );
  13. * rareAutoLoad::register($option);
  14. *
  15. * Refers to the symfony class Automatic loading
  16. * In order to provide efficiency, the location of the class is saved in the cache file, and the file directory in dirs will be scanned when used for the first time
  17. * The file naming requirement for classes that need to be automatically loaded must be .class. php ends. For example, the class defined in the file name a.class.php can be scanned and the file a.php will be ignored
  18. * There is no relationship between the class name and the file naming. For example, class b can be defined in the a.class.php file. {}
  19. *
  20. * @author duwei
  21. *
  22. */
  23. class rareAutoLoad
  24. {
  25. private static $instance=null;
  26. private static $registered=false;
  27. private $cacheFile=null;
  28. private $classes =array();//Corresponding class class name and corresponding file path
  29. private $option;
  30. private $hand=false;//Whether to manually run the script to scan the class path,
  31. private $reloadCount=0;//reload Number of operations
  32. /**
  33. * @param array $option requires parameters dirs: scan directory cache: cache files
  34. */
  35. public function __construct($option){
  36. if(!isset($option['suffix'])) $option['suffix']=".class.php ";//File suffix
  37. $this->option=$option;
  38. if(!isset($option['cache'])){
  39. $trac=debug_backtrace(false);
  40. $calFile=$trac[2 ]['file'];
  41. $option['cache']="/tmp/rareautoLoad_".md5($calFile)."_".filemtime($calFile);
  42. @unlink($option['cache'] );
  43. }
  44. if(isset($option['hand']))$this->hand=(boolean)$option['hand'];
  45. $this->cacheFile=$option['cache' ].".php";
  46. $this->getClasses();
  47. }
  48. /**
  49. * Get the single instance object of DAutoLoad
  50. * @param array $option
  51. * @return DAutoLoad
  52. */
  53. private static function getInstance($option){
  54. if (!isset(self::$instance )){
  55. self::$instance = new rareAutoLoad($option);
  56. }
  57. return self::$instance;
  58. }
  59. /**
  60. * Register for automatic loading
  61. * @param array $option array('dirs'=>'/www/lib/share/,/www/lib/api/','cache'=>'/tmp/111111. php');
  62. * @throws Exception
  63. */
  64. public static function register($option) {
  65. if (self::$registered)return;
  66. // ini_set('unserialize_callback_func', 'spl_autoload_call');
  67. if (false === spl_autoload_register(array(self::getInstance($option), 'autoload'))) {
  68. die(sprintf('Unable to register %s::autoload as an autoloading method.', get_class(self::getInstance())));
  69. }
  70. self::$registered = true;
  71. }
  72. / **
  73. * spl_autoload_call calls load class
  74. * If the path of the class in the cache file is incorrect, it will try to reload once
  75. * Record the key of the class that does not exist after reloading, and mark it as false to avoid multiple invalidation of the cache file. Update
  76. * When using class_exists for judgment, the autoload operation will be performed by default
  77. * @param $class
  78. * @return
  79. */
  80. public function autoload($class){
  81. if(class_exists($class, false) || interface_exists($class, false)) return true;
  82. if ($this->classes && isset ($this->classes[$class]) ){
  83. $file=$this->classes[$class];
  84. if(!$file)return false;
  85. if(!file_exists($file) && ! $this->hand){
  86. $this->reload();
  87. return $this->autoload($class);
  88. }
  89. require($file);
  90. return true;
  91. }{
  92. $this ->reload();
  93. if(isset($this->classes[$class])){
  94. $file=$this->classes[$class];
  95. if(!$file)return false;
  96. require($file);
  97. return true;
  98. }else{
  99. $this->classes[$class]=false;
  100. $this->saveCache();
  101. }
  102. }
  103. return false;
  104. }
  105. /**
  106. * Get the list of class names
  107. * @return
  108. */
  109. private function getClasses(){
  110. if(file_exists($this->cacheFile)){
  111. $this->classes=require($this->cacheFile);
  112. if(is_array($this->classes))return true;
  113. }
  114. $this->classes=array();
  115. $this->reload();
  116. }
  117. /**
  118. * Rescan again
  119. * and save the location information of the class name to cache
  120. * @return
  121. */
  122. private function reload(){
  123. $this->reloadCount++;
  124. if($this->hand)return;
  125. $cachedir=dirname($this->cacheFile);
  126. $this->directory($cachedir);
  127. if(!is_writable($cachedir)) die('can not write cache!');
  128. settype($this->classes, 'array');
  129. $dirs=$this->option['dirs'];
  130. if(!is_array($dirs)) $dirs=explode(",", $dirs);
  131. $dirs=array_unique($dirs);
  132. foreach($dirs as $dir){
  133. if(!$dir || !file_exists($dir))continue;
  134. $this->scanDir($dir);
  135. }
  136. $this->saveCache();
  137. }
  138. private function saveCache(){
  139. if($this->hand)return;
  140. $phpData=" if(!is_array($this->classes))$this->classes=array();
  141. ksort($this->classes);
  142. $phpData.="return ".var_export($this->classes,true).";";
  143. file_put_contents($this->cacheFile, $phpData,LOCK_EX);
  144. clearstatcache();
  145. }
  146. /**
  147. * Scan folders and files
  148. * Only files named by $this->option['suffix'] will be scanned
  149. * @param $dir
  150. * @return
  151. */
  152. private function scanDir($dir){
  153. $files=scandir($dir,1);
  154. foreach($files as $fileName){
  155. $file=rtrim($dir,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$fileName;
  156. if(is_dir($file) && strpos($fileName,'.')!==0){
  157. $this->scanDir($file);
  158. }else{
  159. if($this->str_endWith($fileName,$this->option['suffix'])){
  160. preg_match_all('~^s*(?:abstracts+|finals+)?(?:class|interface)s+(w+)~mi', file_get_contents($file), $classes);
  161. foreach ($classes[1] as $class){
  162. $this->classes[$class] = $file;
  163. }
  164. }
  165. }
  166. }
  167. }
  168. private function directory($dir){
  169. return is_dir($dir) or ($this->directory(dirname($dir)) and mkdir($dir, 0777));
  170. }
  171. function str_endWith($str,$subStr){
  172. return substr($str, -(strlen($subStr)))==$subStr;
  173. }
  174. }
复制代码


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools