TalkPHP
 
 
Account Login
Latest Articles
» cURL Basics
» Securing your PHP applications Part 1
» The way the function rolls
» Database Abstraction with Zend_Db - Part 2
» CSRF POST Token Protection
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack Thread Tools Display Modes
Old 11-13-2007, 02:15 PM   #1 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 434
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, 06:30 PM   #2 (permalink)
TalkPHP Loves You
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Nottingham
Posts: 1,421
Thanks: 68
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, 07:31 PM   #3 (permalink)
Super Moderator
Advanced Programmer 
 
bluesaga's Avatar
 
Join Date: Sep 2007
Posts: 164
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, 05:24 AM   #4 (permalink)
The Contributor
 
Join Date: Nov 2007
Location: California
Posts: 49
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, 12:00 PM   #5 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 434
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, 12:40 PM   #6 (permalink)
The Gregarious
Upcoming Programmer Inquisitive 
 
Join Date: Sep 2007
Posts: 535
Thanks: 64
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, 12:51 PM   #7 (permalink)
The Reckoner
Advanced Programmer Top Contributor 
 
Karl's Avatar
 
Join Date: Sep 2007
Posts: 434
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, 01:21 PM   #8 (permalink)
The Frequenter
Advanced Programmer Top Contributor Good Samaritan 
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 363
Thanks: 20
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
__________________
There's nothing an agnostic can't do if he doesn't know whether he believes in anything or not
sketchMedia is offline  
Reply With Quote
Old 12-04-2007, 01: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
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
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 10:08 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0