Saturday, February 20, 2010

Require, Include, Once, Autoload?

I have seen a few PHP performance tips lately that have me worried. A common tip found, is something along the lines of "Don't use require_once/include_once" and also "Don't use autoload." The implications of following these tips are troublesome to say the least.

Require_once and include_once are PHPs equivalent to Cs #include with an include guard. Not using these, and not using the autoload facility essentially forces one to create a single super-include script, maintaining which will cost a lot of (wasted) time.

It has become common practice to declare and implement classes in their own respective file. To use such a class, one has to include the file containing the class somehow. If this class is only needed in one other place, why bother putting it in its own file? In bigger, more complex applications, code reuse and modularity is a must. And there should be only one place for a certain (reusable) piece of code and one only.

So how should this be accomplished, or more accurately how can this be generically, pragmatically and efficiently achieved without require_once, include_once or autoloading? What about order of inclusion? Redeclaring a function or a class is a fatal error in PHP, so care - which equals time and developer effort - is needed when organizing includes (without using require_once/include_once or autoloading).

While not using any of these three is certainly a way to gain a (tiny) bit of performance, the effect it has on the development effort of larger applications is detrimental. I think, these tips, taken out of sensible context, are even so bad they shouldn't even be mentioned at all. If you really want to gain performance, switch from require_once/include_once to autoloading and use an opcode cache for PHP.

No comments:

Post a Comment