开发者

Lazy Classes Includes PHP

I use a autoloader to include classes. What i'm doing right now is using "glob" to read different dir's and push them in an array. Is there a better solution to this?

$path =开发者_StackOverflow './';

$files = array_merge(
glob($path.'includes/classes/system/*.class.php'),
glob($path.'includes/classes/system/baseclasses/*.class.php'),
glob($path.'includes/classes/system/systementities/*.class.php'));

EDIT:

I use this inside an autoload class. The problem is that I have to search for the files with glob. Is there a faster way to do this?


Autoloading will be triggered whenever you are trying to use a class that isn't know to PHP. If you use include/require, PHP will go through all the directories you specified for your include_path in PHP.ini, so there should no reason to use glob. In your case, it should be sufficient to set the include_path to

/path/to/includes/classes/system/

The fastest way to include files would be to use a class2file map. However, this requires you to create such a map and keep it updated when you modify your application.


PHP has already solved this problem for you. Use PHP's built-in autoloader. Never roll your own when the language/framework provides it for you.


function __autoload($class) {
  $classfile = $class.'.class.php';
  $path = './includes/classes/system/';
  if (is_file($path.$classfile)) require_once($path.$classfile);
  if (is_file($path.'baseclasses/'.$classfile)) require_once($path.'baseclasses/'.$classfile);
  if (is_file($path.'systementities/'.$classfile)) require_once($path.'systementities/'.$classfile);
}

...which is still not the greatest way, but it gets you around using glob(). If you are commonly loading all of your systementities there should be a hard-coded require() list in a boot/config script. There are a lot of options on how to organize and fetch class files. To reduce the time searching for scripts you could think of your filetree as an interface. For the sake of simplicity, you could put all non-mandatory classes in the same folder, reducing the is_file() calls down to one.

In my system I have object classes grouped in folders with their respective control scripts and views. My __autoload() function has a simpler job --

$classfile = $path.$class.'/'.$class.'_class.php';
if (is_file($classfile)) require_once($classfile);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜