Question

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 ?

Do you think is what I described a legitiate use case for procedural code ? Is there a middle ground between this and an object oriented approach with a full fledged framework like Zend framework for instance ? 

Was it helpful?

Solution

There is nothing so bad that it cannot be used as a bad example, at least. To me, your example is not even "formally object oriented", it is just as procedural as the original. The only noteable thing you changed is the namespace where the search function "lives".

A customer object should represent the data and some business logic of a customer (there is not even one attribut in your class, and the search method does not work on a customer object). A "search" function for customers could return a customer object, or a collection of customer objects (echoing some json string has nothing to do with that). Such a function is probably not a member function of a customer class (it could be placed there as a static function, or somewhere else, for example, in a CustomerFactory). And a reasonable customer search should avoid coupling to global attributes and methods (like $options, Db, or Auth::authenticate).

So if your goal is to introduce more "object oriented structure" into your program, you may be better off by doing a little bit more upfront design first. For example, start by designing a customer class first and think about how a search function must look like for delivering such objects.

Licensed under: CC-BY-SA with attribution
scroll top