PHP class automatic loading

Source: Internet
Author: User
Tags autoload php class

The rare has built-in class auto-mount functionality that is used directly without a require (include) class file when using a class.

This kind of automatic loading function is very independent, if you need, you can directly in other frameworks (any PHP program) to use.

1. First introduce rareAutoLoad.class.php

2. Registration function

  1. /**
  2. * Class Automatic loading
  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 from those directories
  8. * ' cache ' = '/tmp/111111.php ',//class path cache file
  9. * ' suffix ' + '. class.php '//suffix for PHP class files that require class auto-loading
  10. * "Hand" =>true,//whether to manually update the class path file, False when the cache file is written to the specified cache file,
  11. *//to TRUE is required to manually allow the autoload.php file
  12. * );
  13. * Rareautoload::register ($option);
  14. *
  15. * Reference to Automatic loading of symfony classes
  16. * To provide efficiency, the location of the class is saved to the cache file, and the file directory in the dirs is scanned at the first use
  17. * File naming requirements for classes that require automatic loading must end with. class.php, such as classes defined in file name a.class.php can be scanned and a.php files are ignored
  18. * Class name and file name can have no relationship, such as the a.class.php file can be defined class b{}
  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 ();//corresponds to class name and corresponding file path
  29. Private $option;
  30. Private $hand =false;//Whether to run the script manually for class path scanning,
  31. Private $reloadCount number of =0;//reload operations
  32. /**
  33. * @param array $option requires parameter dirs: Scan directory cache: Cached file
  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 Dautoload Single-instance objects
  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 (The sprintf (' Unable to register%s::autoload as a autoloading method. ', Get_class (Self::getinstance ())));
  69. }
  70. Self:: $registered = true;
  71. }
  72. /**
  73. * Spl_autoload_call Call Load Class
  74. * If the path to the class in the cache file is incorrect, try Reload once
  75. * Record its key in the class cache that does not exist after reload, mark it as false to avoid the cache file multiple invalid updates
  76. * AutoLoad action is performed by default when using Class_exists
  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 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. * Re-scan once
  119. * and save the location information of the class name in the 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 $this->option[' suffix ') will be scanned to
  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*: abstract\s+|final\s+)? (?: 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. }
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.