Last Updated: June 11, 2021
·
4.919K
· lastguest

PHP: Procedural to Object Oriented API

If you want to to port old procedural-only API to a new shiny object oriented fashion, a proxy class is your solution.

For example, we will expose the old procedural call for the cURL lib with an self-contained, object oriented API.

From the PHP documentation for cURL lib :
http://www.php.net/manual/en/ref.curl.php
we can see that cURL functions all starts with curl_ and all of them ( only exception for curl_init and curlmultiinit ) wants the curl resource as their very first parameter.

We start building a container class for storing the current curl resource as a private property :

class cURL {
    private $curl = null;       
}

and we write a __call magic method for proxying calls to their procedural version, with the "curl_" prefix omitted for syntactic sugar.

public function __call($n,$p){
    if($n=='init' || $n=='multi_init'){
        return $this->curl = 
               call_user_func_array('curl_'.$n,$p);
    } else {
        array_unshift($p,$this->curl);
        return call_user_func_array('curl_'.$n,$p);
    }
 }

Now we add a constructor to our class for initializing the resource

public function __construct($url = null){
    return $this->init($url);
}

And finally we have our complete class:

class cURL {
    private $curl = null;

    public function __construct($url = null){
        return $this->init($url);
    }

    public function __call($n,$p){
        if($n=='init' || $n=='multi_init'){
            // Close resource if opened
            if($this->curl) curl_close($this->curl);
            return $this->curl = call_user_func_array('curl_'.$n,$p);
        } else {
            array_unshift($p,$this->curl);
            return call_user_func_array('curl_'.$n,$p);
        }
    }
}

And this is an example of use

$http = new cURL("http://graph.facebook.com/CaffeinaLab");

$http->setopt(CURLOPT_HEADER, 0);
$http->setopt(CURLOPT_RETURNTRANSFER, 1);
echo $http->exec();
$http->close();

You can find the class and the example here :
https://gist.github.com/lastguest/4740772