Since the introduction of PHP5, us programmers have been treated to an abundance of magic methods. These are used in classes and provide extra functionality. They also tend to save a lot of time.
I'm here to introduce my favourite magic method,
__call(). I use this predominantly within my database files (models in an MVC framework). It allows me to create the functions below without having to write them out individually as they all bring back effectively the same data.
- getColumnByColumn()
- isColumn()
The items highlighted in bold are the crucial parts of the string. The parts that are not bold are just there to give the function name some meaning.
Let's take my member class as a prime example. You often find yourself wanting to get just one column. I could write the functions out individually like so:
- public function getUsernameByEmail($szUsername)
- public function getBirthByName($szDate)
The above functions would, in essence, return to me an email from the first function, and the birth date from the second. However, to save on the fingers it'd be great to bundle those into one function -
__call()!
We can compile the
__call() function like so to accept our
getSomethingBySomething() function and extract out the elements we need to query the database.
PHP Code:
public function __call($szName, $aArgs = null)
{
if(eregi('^get(.*)By(.*)$', $szName))
{
$aKeywords = array();
preg_match_all('/^get(.*)By(.*)$/iU', strtolower($szName), $aKeywords);
}
...
That would extract the two items from out of the
$szName variable and input it into
$aKeywords array allowing me to query the database later on in the script. This is what happens when I create a
__call() function and then call it using my snippet of code above:
- I call a member function like: $pMember->getNameByEmail('test@demo.com');
- PHP checks to see if the function getNameByEmail() exists, if not it checks to see if __call() exists.
- Feed the getNameByEmail() into __call() as the first argument, and any arguments inside the parenthesis as the second argument as an array.
- Checks to see if the first argument matches the regular expression pattern;
- If it matches, extract the two table columns (name and email) from the string and then continue;
- Query the database using the two previously extracted keywords and use the __call() function's second argument, $aArgs, to get the string to check the email column in the database for.
- Return the data and proceed to echo out the data.
...And that's it! Your query is ready to be compiled like so:
PHP Code:
$szSQL = sprintf(" SELECT `%s`
FROM `categories_list`
WHERE `%s` = %s
LIMIT 1",
$aKeywords[1][0],
$aKeywords[2][0],
mysql_parse_value($aArgs[0]));