Search code examples
phpspl

Remove repetitive, hard coded loops and conditions in PHP


I saw this question asked about C# I would like an answer for PHP. I have some old code that has 4 pages of foreach loops and conditions which just makes it hard to read and follow. How would I make this more OO? I was thinking of using SPL Functions but don't fully understand whats involved yet.


Solution

  • This code can probably be cleaned up significantly, and pushed far in the direction of OO, without touching SPL.

    SPL is only needed if you want to alter normal object behaviour in language constructs like foreach(), or in builtins like count(), or in array access funcitons (both operator [] and functions like key(), next() etc).

    Cleanup suggestions:

    • If the same action is performed several (more than 1 or 2) times in the code, break it out into a function. If this action is to be performed on all elements in a array, consider using array_walk. If walking the array doesn't fit for some reason, use a loop :)
    • If you have several instances of some semantically connected data more complex than a key:value pair, with associated operations, consider wrapping it in a class. But a formally documented assoc. array might suit you just as well. Depends on your style, and on the type of data. The important thing here is the structuring of methods working on th data, and the documentation. Doesn't really matter if you make it a class or not.
    • After you have done the above steps, break the newly written functions and objects out into separate include files. I tend towards wrapping most everything in a class, so I mostly have one class pr. file. But some helper classes share a file with the main class, etc. You'll get a feel for it.