To simplify the code required to demonstrate the use of the previous user mapper class, in this section I’m going to define a basic autoloader. It will permit you to include all of the classes shown before through a unique, centralized point. The logic implemented by the autoloader is very trivial; it looks like this: (Autoloader.php)
<?php
// register default autoloader class spl_autoload_register(array('Autoloader', 'autoload'));
// define class 'Autoloader' class Autoloader { public static function autoload($class) { if (class_exists($class, FALSE)) { return TRUE; } $file = $class . '.php'; if (!file_exists($file)) { require_once 'ClassNotFoundException.php'; throw new ClassNotFoundException('The file containing the requested class was not found.'); } require_once $file; unset($file); if (!class_exists($class, FALSE)) { require_once 'ClassNotFoundException.php'; throw new ClassNotFoundException('The requested class was not found.'); } } } If you’ve ever developed autoloader classes before, you’ll find the definition of the above one easy to follow. It behaves like a basic wrapper for the “require_once” PHP construct. In addition, you can see that the autoloader will throw a custom exception at the appropriate places when a requested file or class is not found. So, below I included the file that contains this user-defined exception class: (ClassNotFoundException.php)
<?php
class ClassNotFoundException extends Exception{} Now that there exists an autoloader that will lazy load all the sample classes listed in the preceding segment, we're finally ready to put the previous user mapper class into action. Therefore, in the last segment I’m going to code a script that will show how to use the mapper to translate data stored in a MySQL table into user domain objects, and vice versa. To understand the details of this process, read the following section.
blog comments powered by Disqus |
|
|
|
|
|
|
|