Two implementations of PHP auto loading

  • 2020-03-31 20:53:34
  • OfStack

There are two ways to automatically load PHP.
The first scheme USES successive autoload, which is simpler and weaker.
One problem that hasn't been resolved is whether there is a problem with the file before include.
 
set_include_path('aa' . PATH_SEPARATOR . get_include_path()); 
function __autoload($className) 
{ 
//If you add this detection, because the file is not in the current directory, it will not detect the existence of the file,
//But include works
if (file_exists($className . '.php')) { 
  include_once($className . '.php'); 
} else { 
exit('no file'); 
} 
} 
$a = new Acls(); 

The second option USES SPL to automatically load, and I'm going to talk about that here.
Spl_autoload_register ()
A simple example
 
set_include_path('aa' . PATH_SEPARATOR . get_include_path()); 
//function __autoload($className) 
//{ 
// if (file_exists($className . '.php')) { 
// include_once($className . '.php'); 
// } else { 
// exit('no file'); 
// } 
//} 
spl_autoload_register(); 
$a = new Acls(); 

Spl_autoload_register () automatically calls spl_autoload() to look for ".php" programs with lowercase file names in the path.
In the case of missing, you can also find by defining their own functions
Such as
The function loader1 ($class)
{
// write some load code yourself
}
The function loader2 ($class)
{
// when loader1() cannot be found, I will look for it
}
Spl_autoload_register (' loader1 ');
Spl_autoload_register (' loader2 ');
There could be more...
How does the MVC framework implement auto-loading
So let's set the path
'include' = > Array (' application/catalog/controllers', 'application/catalog/models'), $include = array (' application/controllers',' application/models', 'application/library');
Set_include_path (get_include_path().path_separator. Separator DE (PATH_SEPARATOR, $config['include']);
After getting the URL, parse out the controller and method.
Then set the auto load
 
class Loader 
{ 
 
public static function autoload($class) 
{ 
$path = ''; 
$path = str_replace('_', '/', $class) . '.php'; 
include_once($path); 
} 
} 
 
spl_autoload_register(array('Loader', 'autoload')); 

Routing, instantiating the controller, calling the method, and what you write is executed
 
 
public function route() 
{ 
if (class_exists($this->getController())) { 
$rc = new ReflectionClass($this->getController()); 
if ($rc->hasMethod($this->getAction())) { 
$controller = $rc->newInstance(); 
$method = $rc->getMethod($this->getAction()); 
$method->invoke($controller); 
} else 
throw new Exception('no action'); 
} else 
throw new Exception('no controller'); 
} 

The initial auto-load is complete

Related articles: