Tutorial :Rewriting a midsize application in OO


What are some apraoches i can take to rewrite fairly large procedural php roughly 2000 lines of code app as an oo app. And should i even try to do so, or should i build on top of the existing app? I wrote it when i was learning programming and i now i want to expand it.


There is no silver bullet. However, you could do a lot worse than picking up this book: http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052


I would probably do the following, converting the app into MVC:

  1. Identify the purpose of each function (is it handling the request parameters, outputting data, querying the database?)
  2. Try to refactor functions that do all of the above by splitting them into functions doing nothing more than one of those things.
  3. For each function, try to find a suitable top object/class that can contain this function as a method

    function addUserRecord($dbHandle, $userData) {[...]}   // Becomes  class User {      private $db;      public function addUser($data) {          [...]      }  }  
  4. For each separate *.php-file that is accessible from the outside, turn it into an action of a corresponding controller:

    http://foo.bar.com/user/addUser.php // becomes

    Corresponding controller, using Zend_Framework

    class UserController extends Zend_Controller_Action {      public function addUserAction () {         [...]      }  }  
  5. Move all output specific stuff, such as echoing, into views.

The hardest part will probably be to create proper models, but it is very important and will be the foundation of your application.


If you wish to add new features or significantly extend the application then improve the existing code base as you go. Always check in code better than you check it out. But it would not be a good use of time to do a big rewrite.

Writing tests that prove the important business requirements are being met by the existing legacy code base will help you too. Then you can change the legacy code in the knowledge that you're not breaking the application. If you do break something you'll know what, roughly why, and be able to fix it quickly.


The advantages of well designed OOP is that your components are easily reusable and that it simplyfies team work. Ant then again it's more simple to support code, where you know where is what, and in OO you can find it just by classnames. So you decide if you need it. Sometimes more is less...

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »