TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 09-06-2007, 09:02 PM   #1 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
My Favourite PHP Magic Method: __call

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])); 
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 09-06-2007, 09:12 PM   #2 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 437
Thanks: 22
Karl is on a distinguished road
Default

Nice contribution Wildhoney. The magic functions are a great tool to have in your PHP development toolbox.
Karl is offline  
Reply With Quote
Old 09-06-2007, 10:06 PM   #3 (permalink)
The Frequenter
Prolific Welcomer Upcoming Programmer 
 
Join Date: Sep 2007
Posts: 360
Thanks: 24
Haris is on a distinguished road
Default

Wow, powerful.
Haris is offline  
Reply With Quote
The Following User Says Thank You to Haris For This Useful Post:
TlcAndres (12-28-2007)
Old 09-06-2007, 11:53 PM   #4 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Default

The magic functions are extremely powerful and can be used to create some very impresive frameworks! Nice contribution!
bluesaga is offline  
Reply With Quote
Old 09-13-2007, 09:23 AM   #5 (permalink)
The Wanderer
 
Join Date: Sep 2007
Location: Sydney, Australia
Posts: 19
Thanks: 0
jordie is on a distinguished road
Default

Wow thats really cool :) I never thought of using it like that! At work we're trapped at PHP4 as we need to support as many server setups as possible, so I haven't delved into much of the php5 goodness.
jordie is offline  
Reply With Quote
Old 09-13-2007, 10:36 AM   #6 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

It's a fantastic release. Adds far too much to even consider remembering it all. PHP4 is very limited on the OOP side of things - but PHP5. Wow.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 11-03-2007, 01:46 PM   #7 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

PHP Code:
`categories_list
Is that supposed to be the table where the data is?
Cause what if you have several tables? :S

getUsernameByWarnings(5)

Ofcourse I could store the warnings in a column in the username table, but what if I don't(the warnings was just an example, I'm sure you get the point)??

How would I then be able to search the right table, by using this function?
Tanax is offline  
Reply With Quote
Old 11-03-2007, 02:23 PM   #8 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Default

Well, this was based on an MVC pattern and so that function would be either cloned for every class that represents a table in the database, and so you would change the static table name manually. Or as an alternative, you could make the class central to everything and change the dynamic table name depending on which class you're calling it from.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote
Old 11-03-2007, 04:25 PM   #9 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Yea, but let's say I have a membersclass that deals with all the members.
But I have several tables concerning the members.

Users
Warnings
Logs

For instance.
How would I then base that function on what class, since I'm in the membersclass, but I have several tables concerning the members? ://
Tanax is offline  
Reply With Quote
Old 11-03-2007, 05:13 PM   #10 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Actually I thought of something, the $aArgs is an array?

So if I do like:
PHP Code:
getUsernameByWarnings(5'warnings'); 
PHP Code:
            $sql sprintf("    SELECT `%s`
                    FROM `%s`
                    WHERE `%s` = %s
                    LIMIT 1"
,
                    
$aKeywords[1][0],
                    
mysql_parse_value($aArgs[1]),
                    
$aKeywords[2][0],
                    
mysql_parse_value($aArgs[0])); 
Wouldn't that work?

EDIT:
And that would get every user, who has 5 warnings, from the warnings table.

Last edited by Tanax : 11-03-2007 at 07:35 PM.
Tanax is offline  
Reply With Quote
Old 11-16-2007, 03:32 AM   #11 (permalink)
The Wanderer
 
Join Date: Nov 2007
Location: Mumbai, India
Posts: 24
Thanks: 0
sunilbhatia79 is on a distinguished road
Default PHP5 Magic Tutorials

I have developed a complete set of tutorials on PHP5 Magic Methods, you can read it here:

http://www.sunilb.com/category/php/php5-magic-methods

Hope this helps.

Also if you have any questions, please post them here or leave comments my blog.
__________________
Sunil Bhatia www.twitter.com/sunilbhatia79 - Follow me on Twitter
PHP5 Tutorials
Career Articles
sunilbhatia79 is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 03:13 AM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design