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 11-13-2007, 03:15 PM   #1 (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 Working with Interfaces

When you create an interface, you're basically creating a prototype/blueprint of functions that classes using the interface must implement in order to be valid. It's usually easier to learn from example, so here's a basic interface that represents a Page.

PHP Code:
interface PageInterface
{
    public function 
render();

PageInterface specifies that any classes which implement this interface must also implement a public render() function. It's important to note that you must implement the functions with the same visibility (or weaker) - by visibility I am referering to public/private/protected. In this example, any classes implementing PageInterface must also implement render as a public function containing no arguments.

Here are two classes that implement PageInterface. Notice how both classes contain the public render function (without arguments), if you fail to declare this function PHP will throw a fatal error.

PHP Code:
class Login implements PageInterface
{
    public function 
render()
    {
        return 
'Render Login Page';        
    }
}

class 
Register implements PageInterface
{
    public function 
render()
    {
        return 
'Render Register Page';
    }

So what exactly are interfaces for? In the above example I used them to tie together conceptually similar classes. That is, classes that represent something similar. The above classes, Login and Register, represent a Page, this is the concept that ties the classes together. In other words, they provide an interface (prototype) for building classes of similar concepts.

As we've defined both Register and Login as types of PageInterface we can treat them as the same (as types of Page, anyway). Let's say, for some reason you wanted to create collections of pages and render them together -- you probably wouldn't, but it provides a good base for this example -- then you can use the PageInterface to ensure that this collection of Pages all follow the same interface. Since they all follow this interface, they will all implement the render() function.

PHP Code:
class PageCollection
{
    private 
$pPage = array();
    
    public function 
add(PageInterface $pPage)
    {
        
$this->m_aPageCollection[] = $pPage;
    }
    
    public function 
renderPages()
    {
        foreach (
$this->m_aPageCollection as $pPage)
        {
            echo 
$pPage->render();
        }
    }

In the previous class we've used type-hinting to limit the add methods argument $pPage to a class that implements PageInterface. This will stop the user from passing in an instance of a class that doesn't implement this interface.

Inside the renderPages() method, when we're looping through the collection of pages, we can happily call $pPage->render() because we prohibited the add method from adding anything that doesn't implement PageInterface, and since PageInterface specifies the render() method, we know that $pPage must also have a render() method.

This is a good example of polymorphism: When we call render() we know that it will render a page, but we don't know what sort of page we're rendering. Thus, the render() function has many forms (polymorhpism, means many-forms), because it can render a Login page, Register page, or any other "form" of page.

Here's an example of how the class can be used to create and render a collection of pages.:

PHP Code:
$pPageCollection = new PageCollection();
$pPageCollection->add(new Login());
$pPageCollection->add(new Register());
$pPageCollection->renderPages(); 
Trying to add an invalid class would cause a fatal error, thanks to type-hinting and the use of interfaces.

PHP Code:
$pPageCollection = new PageCollection();
$pPageCollection->add(new Login());
$pPageCollection->add(new Register());

// Try to add a DateTime object, this will cause a fatal error
$pPageCollection->add(new DateTime());

$pPageCollection->renderPages(); 
One other major benefit of using interfaces is that unlike subclassing, you're not limited to single inheritance, you can implement mulitple interfaces for a single class. For example, we could create an admin page interface that could specify all pages implementing the interfaces must contain an auth() method. We could then combine this with the PageInterface to create a class that implements two interfaces:

PHP Code:
interface AdminPageInterface
{
    public function 
auth();
}

class 
AdminNews implements PageInterfaceAdminPageInterface
{
    public function 
auth()
    {
        echo 
"Auth Code";
    }
    
    public function 
render()
    {
        echo 
"Render Code";
    }

Obviously the previous example is functionally useless, it does, however, outline the process of implementing multiple interfaces. I think I'll end the article here, and wrap up by saying that interfaces provide a method to specify a prototype for building classes - from another point of view, they allow you to tie together classes that share a similar concept (the interface).
__________________
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Karl is offline  
Reply With Quote
Old 11-13-2007, 07:30 PM   #2 (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

Good article, I've been recently getting into interfaces, too. They really do add a lot to your code, and as you can type hint them, they stop a scripter coming along and messing it all up.
__________________
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-13-2007, 08:31 PM   #3 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 165
Thanks: 0
bluesaga is on a distinguished road
Default

Great article Karl, however it does seem a little excessive? I just can't see why and where you would use something similar to what you have used it for?

Personally, i would think a good example of abstracts and interfaces would be when creating a factory class for a database and using it for the DB type selector classes.

However, other than the realism of the example the article is great and really informative :) Good work.
__________________
Halo 3 Cheats
bluesaga is offline  
Reply With Quote
Old 11-14-2007, 06:24 AM   #4 (permalink)
The Contributor
 
dschreck's Avatar
 
Join Date: Nov 2007
Location: California
Posts: 82
Thanks: 0
dschreck is on a distinguished road
Default

Nice write up.

As far as how interfaces and abstract classes work differently, here's the first things that come to mind..

Firstly, an interface is great because you can stack them, and they enforce the rules of a framework. You can work up crazy interfaces for each section or module you may want to implement, or just come up with a general sense of what you'll need for classes to work together.

I personally prefer to use only one or two interfaces, and rely upon abstract classes to do a lot of the dirty work. The great thing about abstract classes, in my opinion, is that they can actually contain larger chunks of my most common methods, and dictate my future methods.

Using them together can add some benefits if you dont want to always rely upon polymorph ism. If you always know that you need to have certain methods, that will need to be declared, but you don't want to continuously extend your classes downwards.

Dunno if any of that helps, just some of the things that popped into my head as I read the write up / comments.
dschreck is offline  
Reply With Quote
Old 11-14-2007, 01:00 PM   #5 (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

Thanks for the replies. Bluesaga, yes you're right, I could have given a better example, maybe I can release an actual tutorial demonstrating how to use this for something practicle.

Also thanks for the comparison with Abstract classes dscreck - should help someone. I did want to fit this in, but I felt it would bulk out the article so I decided to keep it purely interface based.
__________________
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Karl is offline  
Reply With Quote
Old 11-14-2007, 01:40 PM   #6 (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

Great article!
Is there any extended, more detailed/advanced article on talkphp about abstract classes and how to use them??
Tanax is offline  
Reply With Quote
Old 11-14-2007, 01:51 PM   #7 (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

Unfortunately not at the moment. Hopefully one of us will get around to it soon.
__________________
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Karl is offline  
Reply With Quote
Old 11-14-2007, 02:21 PM   #8 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

Great article Karl m8.

Quote:
Personally, i would think a good example of abstracts and interfaces would be when creating a factory class for a database and using it for the DB type selector classes.
i agree, it serves a good educational purpose, i have created a tutorial not long ago about that but my explanation of interfaces lacked somewhat more of there powerful capabilities.

this is certainly a better explanation than i gave, and i didnt really explain thier full capabilities i.e. polymorphism (one of the main pillars of OOP) keep up the good work.

We really do need a place to put all these fine tutorials, because they tend to get lost in a forum.

Ciao for now
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
sketchMedia is offline  
Reply With Quote
Old 12-04-2007, 02:19 PM   #9 (permalink)
The Visitor
Newcomer 
 
Join Date: Dec 2007
Posts: 2
Thanks: 0
terdog is on a distinguished road
Default Interfaces

Excellent article, interfaces were entirely foreign to me half an hour ago. I have a good grasp now. Thanks!
terdog is offline  
Reply With Quote
Old 10-18-2012, 02:37 PM   #10 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
dashixiong is offline  
Reply With Quote
Old 10-22-2012, 10:09 AM   #11 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

when I go home.Coach Outlet It’s a big part of what I find addictive about living and working inCoach Outlet Store Online this part of the world. You feel like you’re watching the future unfold.Coach Factory Online for the US Open with no success."I prefer to go day-by-day without setting objectives orCoach Factory Online time frames, work hard on my recovery and make sure I keep on getting better little by little."Nadal has been forced Coach Outletto watch from the sidelines as longtime rival Roger Federer returned Coach Purse Outlet Onlineto the top of the world rankings after winning Coach Factory Outlet Onlinea seventh Wimbledon singles title.He has also seen Britain's Andy Murray,Coach Bags Outlet Online who won the men's singles gold medal at the 2012 Olympic Games, move above him in the world rankings after securing hisCoach Handbags Outlet first grand slam title at last month's U.S. Open.Currently ranked fourth in the world, Nadal has qualified to play at November's season-ending ATP World Tour Finals in London, Coach Outlet Onlinebut his ability to take part is in doubt due to his injury problems, admitting that his knee is still "bothering him".
dashixiong is offline  
Reply With Quote
Old 01-29-2013, 12:57 PM   #12 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Organizers said Coach Outlet Online was opportune because the battle’s 150-year anniversary is in December, and Fredericksburg Coach Factory Outlet has been preparing to mark the sesquicentennial. in the new agreement is that Coach Outlet Online revolutionary councils from 14 Syrian provinces now each have a representative, though not all live Coach Online Outlet in Syria. The hope is that will bind the coalition to those inside the country. Perhaps Coach Bags Outlet the most important body the new group is expected to form is a Revolutionary Military Council Coach Factory Online to oversee the splintered fighting organizations and to funnel both lethal and nonlethal Coach Factory Outlet military aid to the rebels. It should unite units of the Free Syrian Army, various militias Coach Outlet Store Online and brigades in each city and large groups of defectors. Before the ink was even dry on the Coach Outlet Store final draft, negotiators hoped that it would bring them the antiaircraft missiles they crave to Coach Factory Stores take on the Syrian Air Force. The United States and Britain have offered only Coach Handbags Outlet nonmilitary aid to the uprising. A similar attempt by the Syrian National Council to Coach Factory Store supervise the military never jelled. Organizers said funding was too haphazard. Eventually foreign Coach Factory Online governments like Qatar and Saudi Arabia, which are financing and arming the rebels, found Coach Factory Online their own favorite factions to deal with. Foreign leaders notably including Secretary of State Coach Outlet Hillary Rodham Clinton urged this unification largely so they could coordinate their Coach Factory Outlet efforts and aid through a group of technocrats. Once it receives international recognition, the Coach Outlet Store Online coalition is supposed to establish a temporary Coach Outlet Online military never jelled.
dashixiong is offline  
Reply With Quote
Old 02-01-2013, 11:04 AM   #13 (permalink)
The Contributor
 
Join Date: Feb 2013
Posts: 32
Thanks: 0
sara111 is on a distinguished road
Default

Candor Recruitment Agency has strong connections with the world best companies and we make reliable conditions to apply in those companies for our registered clients.
candor employment
candor
jobs agencies
job search websites
job search sites
sara111 is offline  
Reply With Quote
Old 03-02-2013, 04:24 AM   #14 (permalink)
The Wanderer
 
Join Date: Feb 2013
Posts: 18
Thanks: 0
kevinloyed is on a distinguished road
Default

Thanks for a well-written post. I agree with you that post is gives huge advantages.
kevinloyed 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 07:32 PM.

 
     

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