Note that there are some explanatory texts on larger screens.

plurals
  1. PORefactoring a massive function into many files
    primarykey
    data
    text
    <p>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:</p> <pre><code>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 } } </code></pre> <p>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.</p> <p>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 <code>include</code> that file each time:</p> <pre><code>if (file_exists("templates/$nodeName.php")) { include "templates/$nodeName.php"; } else { // do the default thing } </code></pre> <p>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 <code>include</code>s being done now.</p> <p>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 <code>$this</code>, etc.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload