Jump to content
rwhite35

namespace autoloader for custom api

Recommended Posts

Would like some thoughts about this autoloader for namespaces.  Its loosely based on Zend Framework 2 using Composer.  I wanted a simple loader for including my custom classes(ie DB connection, list and forms generations etc) in application modules. Autoloader works as expected so no error to debug, but looking more for improvements or gotcha's I'm not aware of.

This is pseudo code, but the machinery is what's important.

 

./controller_script.php

/* initializes Autoload with an array of namespace strings */
include 'init_autoloader.php';

/* from testspaces.php */
echo Testspaces\Autoload\Tsclass::printSomething(); // outputs This is a simple string.

/* from globalspaces.php */
echo Globalspaces\Autoload\Omnipresent::imEverywhere(); //outputs This is a good hand.

./init_autoloader.php

/**
 * initialize the autoloader for namespaces under the lib directory.
 * this script would be placed in each module where global classes
 * were required, ie DB connections, UI output(lists and forms)
 */
 
/* namespaces array, namespace file name matches first part before first backslash */
$nsarray = array(
	'Globalspaces\Autoload\Omnipresent',
	'Testspaces\Autoload\Tsclass',
	);
	
/* initialize the AutoloaderInit class */
$apath = __DIR__ . "/lib/autoload.php";
if (file_exists($apath)) {
    include $apath;
    $loaderObj = new AutoloaderInit($nsarray);
    $loaderObj->getLoader();
} else {
   echo "Missing autoload.php script, check file path: ".$apath."<br>";
}

lib/autoload.php

class AutoloaderInit {
   private static $loader;
   private static $nsnames; // indexed array of namespace strings defined in init_autoloader
    
   public function __construct($nsarray) {
      self::$nsnames = $nsarray;
   }
   /*
   * callback function called by spl_autoload_register
   * $class passed by reference
   */
   public static function loadClassLoader($class) {
     if ($class) {
       $nameparts = explode('\\', $class);
       $filename = strtolower($nameparts[0]).".php";
       require __DIR__ . DIRECTORY_SEPARATOR . $filename;
     } else {
       throw new Exception("loadClassLoader failed to include ".$filename);
     }
   }
   /*
   * interface method called from initializer
   * $params array $nsnames, array of namespace strings
   * $return void
   */
   public static function getLoader() {
     //error_log("getLoader nsnames: ".var_dump(self::$nsnames));
     if (self::$nsnames) {
        $cnt = count(self::$nsnames);
	for($i=0;$i<=$cnt;$i++) {
          if (null !== self::$loader) return self::$loader;
	  spl_autoload_register(array('AutoloaderInit', 'loadClassLoader'), true, true);
	  self::$loader = $loader = new self::$nsnames[$i]; // new instance of class
        } // close for loop
	spl_autoload_unregister(array('AutoloaderInit', 'loadClassLoader'));
        return $loader;
      } else {
	error_log("No namespaces provided to getLoader");
      }
    }
}

lib/testspace.php

namespace Testspaces\Autoload;

/* a class defined in namespace */
class Tsclass {

   static function printSomething() {
      echo "This is a simple string.<br>";
   }
}

lib/globalspaces.php

namespace Globalspaces\Autoload;

/* another class defined in namespace */
class Omnipresent {
	
   static function imEverywhere() {
	echo "This is a good hand.<br>";
   }
	
}

Share this post


Link to post
Share on other sites

Composer ships with an autoloader, just stick to one of the standards and use that.

Share this post


Link to post
Share on other sites

Thanks for the reply.  Been busy.  I do use Composer for some projects, mainly ZendFramework projects.  But wanted something light weight and simple to configure for my own projects.  Appreciate the feedback, thanks.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.