In this question about including all the classes in a directory for an interpreter that needs all of them, it was suggested that a better way to handle the problem would be to conditionally include only the Command file that is needed for this iteration of the interpreter. For example, instead of this:
require_once('CommandA.php');
require_once('CommandB.php');
require_once('CommandC.php');
class Interpreter {
public function interpret($action) {
switch($action) {
case 'A':
$c = new A();
$c->execute();
break;
}
}
}
Do something more like this:
class Interpreter {
public f开发者_StackOverflow中文版unction interpret($action) {
switch($action) {
case 'A':
require_once('CommandA.php');
$c = new A();
$c->execute();
break;
}
}
}
What are the advantages and disadvantages of going with the second choice -- dynamically and conditionally loading only the needed command -- as opposed to the first one -- including all of the files at the head of the file, C-style?
In the answer given to my previous question, speed, footprint and ease of writing were listed as advantages of conditionally loading. In other questions where this is addressed, I've seen it suggested that c-style loading is more readable and maintainable. Can anyone elaborate on these? Any other advantages or disadvantages?
The main advantage of the conditional loading is that it won't include a whole tree of php files every time you load that class. Event when you use a code cache (and you should), the files are checked for updates every time the vm encounters an /(include|require)(once)?/, so including unnecessary php files will slow down your code.
The disadvantages of this particular method is, that it is harder to maintain, and easier to make mistakes. Writing one thing twice is a code smell. Wirting My_Class means, that you need this class, and writing include "My_Class.php" also means this. This is not right.
I suggest using autoloading: http://php.net/manual/en/language.oop5.autoload.php
精彩评论