Skip to main content
1 of 3

Convert procedural code to object oriented.

I have a PHP application (a web service). It consists of files grouped in directories by theme like :

/customer /search.php

with this example content :

Auth::authenticate($options); $db = new Db($options); $db->query("select ... "); echo json_encode($db->fetch_all();

A basic way to convert this code to object oriented code would be to map a URL /object/method.php to $Object->method($post_parameters) using a basic router. The above example code would become (in file /Customer.php):

class Customer { function search($post_parameters) { Auth::authenticate($options); $db = new Db($options); $db->query("select ... "); echo json_encode($db->fetch_all(); } }

Advantages

  • It is that it is easy to convert the code, it will not take much time.
  • I can use autoloading of the classes.

Disadvantages :

  • It is merely formally object oriented. It still remains mainly procedural code.
  • I still call Auth::authenticate() and create a new Db in each method (but not always with the same parameters).

Am I on the right track ? Is there a better way to approach that code refactoring ? Or is there an obvious next step ?