tags:

views:

288

answers:

5

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.

A: 

Start slowly. refactor it a piece at a time.

If you are looping over a lot of arrays, look at the array functions like array_map, array_walk, and friends. This is more a functional refactoring then an OO refactoring, but it would carry you pretty far. If it made sense to go more OO, then you will have some functions that you could then push into the proper classes as needed.

Jonathan Arkell
+1  A: 
gnud
A: 
Kris Erickson
I just picked up the Refactoring by Fowler book, thanks Kris.
Clutch
+1  A: 

If I were you, I'd start by writing test code.

If you can build up a set of testcases that fully describe the functionality you're refactoring, you can go ahead and rewrite your code safe in the knowledge that it will still work.

PHPUnit might be a good place to start with this.

Mr. Matt
A: 

If I understand you correctly, you have foreach loops (and the like) nested 4 pages deep, and you are wondering if this OO thing you've heard about can help.

You should certainly go ahead and refactor your code to reduce the levels of nesting, and improve the readability, but don't confuse that with Object Orientation.

OO is a way of structuring your code to put the definition of the data structures next to the code that manipulates those data structures. While one of its key goals is to aid readability by providing encapsulations of complexity, OO isn't the only way to do it.

If you don't yet understand the concepts of OO, you may find it easier to refactor your code to separate the code inside the inner loops into separate functions which (hopefully) will each have a single, simple task.

Don't get me wrong; I am an advocate of OO, especially as a technique to provide developers with higher-level concepts to discuss design more efficiently. OO is well worth learning.

But don't let a lack of knowledge about OO stop you from pulling the inner code out of the loops and putting them into single-purpose functions.

(If I have misunderstood your level of OO knowledge, my apologies.)

Oddthinking