Using dynamic methods in your PHP Classes

Hello all!

I was just trying to design an object oriented PHP interface to handle basic CRUD* operations in a PostgreSQL Database, and i came up with the idea of using dynamic methods to call the stored procedures. I’ll try to explain what i did here, and how.

I have a test database which has an “employees” table in it; and a stored procedure called “addEmployee“, with the arguments “name, salary, hire_date“. This procedure returns true if the new record was successfully added to the table.

What i want to achieve was to be able to call this stored procedure directly from PHP, and see what it returns to me. Let’s assume we have an Engine class that connects to the database automatically. I wanted to do something like this :

$engine = new Engine();

$name = "Mehmet Seckin";
$salary = 5600;
$hired = "2013-12-20";

// Adding "Mehmet Seckin"
$engine->addEmployee($name, $salary, $hired);
// Loading a single boolean result.
$result = $engine->loadBoolean();

After a quick google search, i found out PHP (> 5.0.1) has a nice overloading method named “__call()“. This method lets you overload ANY method that is called from your class, which is just what i wanted to do.

__call() takes two arguments, and these are $method, and $arguments; which are speaking for themselves.

Now, when we call a non-existent method;

$myObject->foo("bar","goo");

Our __call() method takes over. $method stands for the method name (“foo”), and $arguments is an array containing the arguments (“foo” and “bar”).

So, i overloaded the __call() method like this :

function __call($method,$arguments) {
$query = "SELECT "$method"(";
foreach($arguments as $argument) {
$query .= "'$argument',";
}
if(count($arguments) > 0) {
// Remove the extra comma
$query = substr($query, 0, strlen($query)-1);
}
$query .= ");";
//...
// Execute query and return the results.
}

And i was able to call any stored procedure directly within PHP, no queries, no fetch_arrays, no trouble…

Feel free to check the actual source code on my github account.

(*) : CRUD stands for Create, Read, Update and Delete.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s