I've been trying to refactor a "bit" of code that I'd previously developed. Basically, the project was my response to not knowing how to use XSLT effectively, so I developed an XML transformation system in PHP. The program reads through the tags of an XML file and does something along these lines to convert it to HTML:
private function getTemplate(...) {
switch ($nodeName) {
case "a" :
// code here to generate a link tag
break;
case "box" :
// code here to generate the divs and whatnot to create a box
break;
case "ref" :
// look up an external reference file and include a bibliography
break;
default :
// do the default thing
}
}
That was all working great, except that I ended up with 26 branches to my switch, and that once switch block was over 1000 lines of code. Needless to say, it made maintenance slightly more difficult.
What I've done now is to pull the code of each branch out into its own file (named "a.php", "box.php", "ref.php" ...) and include
that file each time:
if (file_exists("templates/$nodeName.php")) {
include "templates/$nodeName.php";
} else {
// do the default thing
}
Again, this works, but benchmarking it shows that it has slowed down processing times by 50%. I'm assuming that this is because there's now up to 4000 include
s being done now.
What I was considering was to put the code for each template into a function, and if the function hasn't been declared then include the file, and then run the function - the only problem with that is that the existing code has been written in the scope of the original function, using $this
, etc.
Given that this code is not run in real time (eg: it merely processes the XML into static HTML files which are stored - it's not done on the fly), do you have any advice for me here?