Posted By

AmyStephen on 03/22/10


Tagged

autoloader splautoload


Versions (?)

PHP Autoloader with spl_autoload


 / Published in: PHP
 

URL: http://www.alltogetherasawhole.org/profiles/blogs/joomla-autoloader-using

Autoload for PHP that enables the definition of namespaces and folders in a list that is used in the spl_registered function for any number of unknown values. This specific function can be used with Joomla! 1.5 since it reload's Joomla!'s autoload class at conclusion.

  1. <?php
  2. class TamkaAutoload
  3. {
  4.  
  5. function loadApplicationClasses () {
  6.  
  7. /*** nullify existing autoloads ***/
  8. spl_autoload_register (null, false);
  9.  
  10. /*** specify extensions that may be loaded ***/
  11. spl_autoload_extensions('.php');
  12.  
  13. function TamkaLoader ($class)
  14. {
  15. /*** retrieve namespaces and folders from configuration ***/
  16. $serverConfig = new TamkaServer;
  17. $namespaceArray = explode(",", $serverConfig->autoloadNamespaces);
  18.  
  19. $autoloadFolderArray = explode(",", $serverConfig->autoloadFolders);
  20.  
  21. /*** process each configuration name space ***/
  22. for ($na = 0; $na < count($namespaceArray); $na++) {
  23.  
  24. /*** remove name space value from class to find filename ***/
  25. $classFilename = TamkaAutoLoad::extractFileName ($class, $namespaceArray[$na]);
  26.  
  27. if ($classFilename == false) {
  28. /*** namespace not used for class prefix ***/
  29. } else {
  30. /*** namespace matches ***/
  31.  
  32. for ($fa = 0; $fa < count($autoloadFolderArray); $fa++) {
  33. /*** namespace not used for class prefix ***/
  34. $folderFile = TamkaAutoload::replaceSlashwithDirectorySeparator(TAMKA_BASE.trim($autoloadFolderArray[$fa]).DS.$classFilename);
  35.  
  36. /*** require_once file, if exists, and exist ***/
  37. $results = TamkaAutoLoad::requireFilename ($folderFile);
  38.  
  39. if ($results == true) {
  40. $fa = count($autoloadFolderArray) + 1;
  41. $na = count($namespaceArray) + 1;
  42. }
  43. }
  44. }
  45. }
  46. }
  47.  
  48. /*** register the new loader function ***/
  49. spl_autoload_register('TamkaLoader');
  50.  
  51. /*** RELOAD the Joomla! Autoload ***/
  52. spl_autoload_register('__autoload');
  53. }
  54.  
  55. function extractFileName ($class, $namespace)
  56. {
  57. if (substr($class, 0, strlen($namespace)) == $namespace) {
  58. return trim(substr($class, strlen($namespace), (strlen($class) - strlen($namespace)))).'.php';
  59. } else {
  60. return false;
  61. }
  62. }
  63.  
  64. function replaceSlashwithDirectorySeparator ($filename)
  65. {
  66. return str_replace (chr(47), DS, $filename );
  67. }
  68. function requireFilename ($file)
  69. {
  70. if (file_exists($file)) {
  71. require_once $file;
  72. return true;
  73. } else {
  74. return false;
  75. }
  76. }
  77. }

Report this snippet  

You need to login to post a comment.