In relation to WordPress you have two main functions: get_template_directory()
, get_stylesheet_directory()
, The first of these will look in the theme folder, while the other will look in the child theme directory.
If we combine these, we can make a auto loader, which consists of:
public function get_instance(){
if(null == self::$_instance){
self::$_instance = new self();
}
self::$_directories = array(
get_template_directory(),
get_stylesheet_directory(),
);
return self::$_instance;
}
public function load_class($class){
$path = str_replace('_', '/', $class);
foreach(self::$_directories as $directories){
if(file_exists($directories . '/' . $path . '.php')){
require_once($directories . '/' . $path . '.php');
}
}
}
These functions would obviously belong in a class that is then instantiated. All were doing here is saying, look for a class using naming standards of Folder_SubFolder_ClassName, by substituting '_' for '/' and appending .php to the end. Not that hard.
It works every time. Child theme classes can load parent theme classes and parent theme classes can call each other with out worrying about require_once()
Now lets throw something into the mix. Lets assume your theme uses custom/packages and you have a class in there, the obvious answer is to change the get_instance()
to:
public function get_instance(){
if(null == self::$_instance){
self::$_instance = new self();
}
self::$_directories = array(
get_template_directory(),
get_stylesheet_directory(),
get_template_directory() . '/custom/packages/'
);
return self::$_instance;
}
this way classes, a class such as: PackageName_Folder_SubFolder_ClassName{}
should be loaded because it resides inside custom/packages/PackageName/Folder/SubFolder/ClassName.php
and we told the auto loader, to look in these three places for the class.
so whats the issue?
I get an error stating that PackageName_Folder_SubFolder_ClassName
doesn't exist or cant be found.
Why? What am I doing, or assuming, wrong?