Jump to content

namespace autoloader for custom api


rwhite35
Go to solution Solved by trq,

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>";
   }
	
}
Link to comment
Share on other sites

  • 2 weeks later...

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.