Home Backend Development PHP Tutorial php class automatic loading

php class automatic loading

Jul 25, 2016 am 09:09 AM

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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles