php class automatic loading

WBOY
Release: 2016-07-25 09:09:47
Original
1040 people have browsed it

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. }
复制代码


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!