As I stated previously, developing a file loading system that abstracts the load process a bit further is a straightforward procedure that can be tackled with minimal efforts. Basically, this system will base its functionality on a simple loader class that will behave as a proxy for a “require_once()” function. Imagine now that there are a couple of files that need to be included by a certain PHP application, whose definitions are as follows: ('sample_file1.php')
<?php echo ' This file has been loaded with the Loader class.' . '<br />'; ?>
('sample_file2.php') <?php echo 'This file has been loaded at the following time: ' . date('H:i:s'); ?> Again, it’s fair to say that I’m not going to waste your time (and mine) discussing how the above files do their things. Instead, pay close attention to the signature of the file loading class below, which not surprisingly has been called “Loader().” It looks like this: class Loader { // constructor (not implemented) public function __construct(){}
// load specified file public function load($filepath) { if (!file_exists($filepath) OR is_dir($filepath)) { throw new Exception('The specified file cannot be found!'); } require_once($filepath); } } Despite its rather basic definition, the previous “Loader()” class is a considerable breakthrough when it comes to building a file loading mechanism. It not only acts like a wrapper for the “require_once()” function, but it handles the eventual errors that might occur during the load process in a more elegant way, through native PHP exceptions. At this point, everything is starting to look a bit better. I created a basic loader class, and there are a couple of sample files that need to be included within a fictional application to display some trivial messages on screen. The question that comes up now is: how can these two files be loaded by the previous “Loader” class? Well, it’s quite possible that you’ve already found the answer, but in the last section of this tutorial I’m going to create a hands-on example that will demonstrate how to use this class in a few simple steps. To learn more about how this example will be developed, go ahead and read the next segment.
blog comments powered by Disqus |
|
|
|
|
|
|
|