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:
- Identify the purpose of each function (is it handling the request parameters, outputting data, querying the database?)
- Try to refactor functions that do all of the above by splitting them into functions doing nothing more than one of those things.
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) { [...] } }
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
http://foo.bar.com/user/add-userCorresponding controller, using Zend_Framework
class UserController extends Zend_Controller_Action { public function addUserAction () { [...] } }
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.
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...
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.