Well I currently have a file structure that I believe is kinda unscientific, so I decide to revise it. The old and new file structures are illustrated as below:
Old structure:
classes
abstracts
finals
interfaces
traits
New structure:
library
controller
admincp
base
modcp
site
and more...
model
data
group
item
page
setting
system
user
and more...
helper
resource
core
exception
gui
io
math
native
utility
and more...
view
lang
main
template
and more...
I know it is getting more complicated, and this is definitely giving me a headache on how to redesign my Loader class. As most of you probably know, PHP introduces new ways to define autoload approach so that we do not have to use __autoload() with so many constraints anymore. Here is the loader class I designed for my old structure:
<?php
class Loader extends Object implements Loadable, Extractable{
protected $classes = array();
public function __construct(){
// The Loader object constructor
spl_autoload_register(array($this, 'load'));
}
public function load($class){
// The method that autoloads a class
if(!in_array($class, $this->classes)){
// The class is not yet loaded, it should be a good idea to load
$this->classes[] = $class;
$class_path = strtolower("classes/class_{$class}");
$dir = (defined("SUBDIR"))?"../":"";
if(file_exists("{$dir}{$class_path}.php")) include("{$dir}{$class_path}.php");
else{
$abstract_path = strtolower("classes/abstract/abstract_{$class}");
$final_path = strtolower("classes/final/final_{$class}");
$interface_path = strtolower("classes/interfaces/interface_{$class}");
if(file_exists("{$dir}{$abstract_path}.php")) include("{$dir}{$abstract_path}.php");
elseif(file_exists("{$dir}{$interface_path}.php")) include("{$dir}{$interface_path}.php");
else throw new Exception("Fatal Error: Class {$class} either does not exist!");
}
}
else Throw new Exception("An error has occurred. Class {$class} has already been loaded.");
}
public function extract(){
// This method returns a list of loader method
return spl_autoload_function();
}
}
The Loader::load() method is a bit more complex than you'd imagine, this is because my old class file structure has prefix class, abstract, final and interface to distinguish them from executable view files(this should not be a problem anymore with MVC, at least I hope). With a file structure that only contains 2-5 directories storing class library files, a loader class is very easy to design. But this becomes a problem with my proposed new file structure, in which a class may be found from 20-30+ different library directories. How will you redesign the loader class and its method given this circumstance? Is it enough just to use set_include_path()? Is it gonna help with usage of namespace? If you have any ideas, please lemme know and I'd appreciate more with a bit of dummy examples. Thx.