Domanda

So I am using spl_autoload_register to load my classes. However I have this structure for my classes:

classes
    classfolder
       classfile

So normally when I was including them I was doing this:

include('classes/modules/module_class.php');

Now using spl_autoload_register how would I handle sub folders? I dont have the ability to upgrade to php 5.3 to use namespaces, do I need to do something like this?

$module = new modules_Module();

Then the function I register with spl_autoload_register explodes the _ and uses the first part as the class folder and the second part as the class method. But then I would have to change the class name to modules_Module right? If so is that ok? Or is there a better way of doing this?

È stato utile?

Soluzione

Not saying you should do that, but a common pattern in PHP-land is to use case in the filenames as well and not add stuff like _class or class.Module.php:

include('classes/Modules/Module.php');

In PHP 5.2 (no namespace support), you then work with the _ underscores:

class Modules_Module
{
}

So this is how it is normally done. Not saying that you must do it that way. You can also just resolve as you wish. But one should also know about this more common pattern as it helps reading/navigating third party sourcecode.

Altri suggerimenti

Basically that's it.

In addition to namespaces (which you can't use) and naming conventions on class names (which would need you to rename all your classes) the only other sane option is to build a classmap: an array that maps class names to the full path of the file that defines them.

Going this way means that you have to update the classmap each time classes are added or modified, a task which is a prime candidate for automation. Look into using Composer's autoload functionality, it can do this on demand and generate the autoload code for you automatically. Composer is so good that it's useful even when you disregard 90% of its features.

As long as your files are arranged in some way that let's you go from the class name to the file name, you can implement your autoloader function however you like. Your autoload function needn't just turn the class name into a directory path: it's job is simply to take a class name, and include the right file, if at all possible.

Keeping your mapping relatively simple is useful for humans, too, though - so you know which file to edit.

For instance, you could say that all classes beginning Mod_ live in a directory called classes/modules but all others live in a directory called classes/general.

You can also use file_exists to check multiple possibilities for one class, but bear in mind that this has some cost, both to PHP checking the filesystem, and to the human trying to remember where the file went.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top