note 101190 deleted from language.oop5.autoload by peehaa

From: Date: Mon, 08 Jul 2013 20:56:14 +0000
Subject: note 101190 deleted from language.oop5.autoload by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-195533@lists.php.net to get a copy of this message
Note Submitter: b dot rense at gmail dot com ---- php autoloading is a b*tch, nevertheless, i think the following class is a pretty good solution. <?php class autoload_autoloader { public static $instance; private $_src=array('application/controllers/', 'application/models/', 'application/views/helpers/', 'library/'); private $_ext=array('.php', 'class.php', 'lib.php'); /* initialize the autoloader class */ public static function init(){ if(self::$instance==NULL){ self::$instance=new self(); } return self::$instance; } /* put the custom functions in the autoload register when the class is initialized */ private function __construct(){ spl_autoload_register(array($this, 'clean')); spl_autoload_register(array($this, 'dirty')); } /* the clean method to autoload the class without any includes, works in most cases */ private function clean($class){ global $docroot; $class=str_replace('_', '/', $class); spl_autoload_extensions(implode(',', $this->_ext)); foreach($this->_src as $resource){ set_include_path($docroot . $resource); spl_autoload($class); } } /* the dirty method to autoload the class after including the php file containing the class */ private function dirty($class){ global $docroot; $class=str_replace('_', '/', $class); foreach($this->_src as $resource){ foreach($this->_ext as $ext){ @include($docroot . $resource . $class . $ext); } } spl_autoload($class); } } ?> Obviously you still have to include this class the dirty way, for example: <?php $path='../'; $docroot=$_SERVER['DOCUMENT_ROOT'] . implode('/',array_slice(explode('/',$_SERVER['PHP_SELF']),0,-2)) . '/'; include($path . 'library/autoload/autoloader.php'); autoload_autoloader::init(); ?> please note that this autoloader class does require the $docroot variable which is the absolute path of the root of your application, you can set it manually or copy the code i used. my directory structure looks like this: - www/ + myapp/ + application/ + controllers/ + models/ + views/ + helpers/ + library/ + autoload/ - autoloader.php

« previous php.notes (#195533) next »