0

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?

4

1 回答 1

0

我认为问题是由于 /location/packages 的位置造成的。

在输出的 load_class foreach 循环中放置一个回显$directories . '/' . $path . '.php'。我敢打赌,这会让你弄清楚。您可能需要将 public_html 路径硬编码到自动加载功能中。

于 2013-07-12T19:37:09.037 回答