SitePoint Sponsor

User Tag List

Results 1 to 22 of 22
  1. #1
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    Boston, MA
    Posts
    188
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Interface Confusion...

    I'm pretty good when it comes to OOP -- I know all the big words like inheritance, polymorphism, aggregation, composition, etc. However, the one thing that still kind of confuses me is the "Interface". In PHP Interfaces are just regular classes, they don't have their own type like in Java (as I understand it), beyond that I get a little confused. Take this example:

    PHP Code:
    Class Barkable {
    function 
    bark();
    }

    Class 
    WoofDog implements Barkable {
    function 
    bark() {
    echo 
    "woof";
    }

    Does that make sense? So an interface tells an implementing class what methods it must have. What about this:

    PHP Code:
    Class Barkable {
    function 
    bark() {
    echo 
    "woof";
    }
    }

    Class 
    WoofDog implements Barkable {
    function 
    blah() {}

    Does that make sense, too? Or do all the methods have to be abstract for the interface? Should an interface have member variables? What draws the line between an inherited class and an interface? I guess that's my biggest question there. Help me understand here

  2. #2
    SitePoint Guru dbevfat's Avatar
    Join Date
    Dec 2004
    Location
    ljubljana, slovenia
    Posts
    684
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Interface is sort of an abstract class with all methods public and abstract. It forces the implementing class to define the methods.

    An interface can extend several interfaces. A class can implements several interfaces, but can only extend one parent class.

    Your code is actually wrong - you cannot implement another class, you can only extend from it.
    PHP Code:
    interface Barkable
    {
      function 
    bark();
    }

    interface 
    Movable
    {
      function 
    move();
    }

    class 
    WoofDog implements BarkableWalkable
    {
      function 
    bark()
      {
        echo 
    "woof!";
      }
      
      function 
    move()
      {
        echo 
    "i walk";
      }
    }

    $dog = new WoofDog();
    $dog->bark();
    $dog->move(); 
    As far as "type" is concerned, interface is a type in exactly the same way as the class is. You can check for the type, which actually means checking whether an object is a class or an interface:
    PHP Code:
    $dog = new WoofDog();
    $dog instanceof Barkable // true
    $dog instanceof Movable // true
    $dog instanceof WoofDog // also true, of course

    // or with typehinting
    function force_to_bark(Barkable $barkable)
    {
      
    $barkable->bark();
    }
    force_to_bark($dog); 
    When you juggle with such type checking, there is not difference between classes or interfaces.

    HTH

  3. #3
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    Boston, MA
    Posts
    188
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So really, an Interface is just a set of "rules" for a class implementing it?

    Say I have two classes, Article and News, and I want them to both be "commentable", i.e. people can leave comments on the articles and news posts. This would obviously entail identical functions for each class, such as saveComment() for example. Would it make more sense to have a Commentable interface that each class can implement, or just a stand-alone class that those classes could create an object of to handle comments?

    The way I figure it, most of the functions will be the same for each class (like displayComments() would just output a table of all the comments for example), so would it really make sense to re-define them for every implementing class if it's just going to be copy/paste. I could understand if I could mix in regular functions with the abstract ones, but if they're all abstract it just seems to make more sense to make a standalone class for it.

    Or maybe I just don't really see the greater "point" of Interfaces.

  4. #4
    SitePoint Wizard dreamscape's Avatar
    Join Date
    Aug 2005
    Posts
    1,080
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I could be completely wrong, but it seems to be that Interfaces are of great use and make alot of sense in team environments.

    However, in single coder environments, I'm not really sure what benefit they are. I don't really use them in my own code (single coder environment).

    Now sometimes I will implement an SPL interface; however, the SPL interfaces actually do something and change the behavior of the class in some way (ArrayAccess, Iterator, etc), something that to my knowledge you cannot do with your own interfaces since you can only define required methods.

  5. #5
    SitePoint Guru dbevfat's Avatar
    Join Date
    Dec 2004
    Location
    ljubljana, slovenia
    Posts
    684
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    binjured: not a set of "rules" exactly, but a set of public methods. They can also be viewed as a "role".

    In your case, I'm pretty sure a stand-alone class for comments would be in place. Classes must be tight and focused. Imagine replacing the logic for the comments. If you have the logic in every class, this could be a problem. But if an object uses another object, you can change the comment-logic anytime you want, providing that it's methods (the ones that Article and News call) remain the same - or modify the calls.

    Interfaces are more abstract than classes. Imagine having two classes that don't share a common predeccessor. And you want both to be related in some way, because they have the same behaviour.
    PHP Code:
    class Movable
    {
      function 
    move();
    }

    class 
    Man implements Movable
    {
      ...
    }

    class 
    Dog implements Movable
    {

    These two classes are both Movable, but one is a Man and the other one is a Dog. Because they're both Movable, you can pass them around to any function that takes a Movable object. The function doesn't care what the class is, as long as it has the move() method - which is enforced by the interface.

    To expand on the example:
    PHP Code:
    class LivingBeing {...}

    class 
    Thing {...}

    interface 
    Movable {...}

    class 
    Man extends LevingBeing implements Movable {...}

    class 
    Tree extends LivingBeing {...}

    class 
    Plane extends Thing implements Movable {...}

    class 
    Mountain extends Thing {...} 
    You can see the relations:
    - Man and Tree are both a LivingThing
    - Plane and Mountain are both a Thing
    - Man and Plane are both Movable
    - Tree and Mountain aren't Movable

    Now, consider this:
    PHP Code:
    function move(Movable $m) {...}
    function 
    kill(Thing $t) {...} 
    The move() function needs something that is Movable, which can be a Man or a Plane. It doesn't care if the class of the passed object is LivingBeing or Thing. In layman's words: you can move a Man or a Plane, but not a Tree or a Mountain.

    Likewise, the kill() function can kill a LivingBeing, which can be a Man or a Tree. It cannot kill a Thing.

    Here is an interesting link about interfaces: http://www.artima.com/designtechniques/interfaces.html

    @dreamscape: you're wrong Interfaces have nothing to do with single vs. team coder environment. It has all to do with code abstraction and cohesion. Some interfaces provided by SPL allow you to change the way you access the objects, that's true, but interfaces in general are just a way of abstracting a class to "become something else", no matter what class it is.

    Regards

  6. #6
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So really, an Interface is just a set of "rules" for a class implementing it?
    Interfaces are just that, a set of specs that you need to implement. But PHP doesn't really have interfaces...only abstract classes. You will get in trouble with PHP if you think it really has interfaces.

  7. #7
    SitePoint Addict
    Join Date
    Aug 2003
    Location
    Toronto
    Posts
    300
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Snaily
    Interfaces are just that, a set of specs that you need to implement. But PHP doesn't really have interfaces...only abstract classes. You will get in trouble with PHP if you think it really has interfaces.
    Not a spec -- a calling contract. All it gaurantees is that an interface's abstract methods (and signature!) will be defined in the concrete classes that implement it. They do not gaurantee that called methods will exhibit a specific behaviour (which makes sense since the interface is purely abstract). dbevfat's explanation was very good.

    The rest of your comment concerning PHP's implementation of interfaces wasn't clear to me. Can you clarify?

  8. #8
    SitePoint Zealot
    Join Date
    Feb 2004
    Location
    Boston, MA
    Posts
    188
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the replies!

    @dbevfat: Thank you very much for your in-depth responses, they helped a lot. In the situation I mentioned, it has been determined that a separate class would be best, however would it make sense to also have the Commentable interface, such that in the class Comment functions may exist that can take any "Commentable" class object as a parameter? I cannot think of a specific, concrete example of where this would be advantageous right now, but I can imagine it might be.

    PHP Code:
    interface Commentable {

    abstract function 
    something();

    }

    class 
    Comment {

    private 
    $id;
    private 
    $table;

    function 
    __construct($table$id) {
    // ...
    }

    function 
    write($name,$content) {}

    function 
    read() {}

    function 
    unk(Commentable $c) {}

    }

    class 
    Article implements Commentable {

    var 
    $c;

    function 
    __construct() {
    $this->= &new Comment();
    }

    function 
    something() {}


    I'm not sure what "something()" or "unk(...)" may do, but I think it's conceivable that they could be of some kind of use Or, I guess the abstract function could be dropped all-together and just have one or more functions in the Comment class that use Commentable objects.

    Quote Originally Posted by dreamscape
    Now sometimes I will implement an SPL interface; however, the SPL interfaces actually do something and change the behavior of the class in some way (ArrayAccess, Iterator, etc), something that to my knowledge you cannot do with your own interfaces since you can only define required methods.
    Yes, this is what interested me most about the Interfaces; the fact that some of the SPL interfaces do pretty cool stuff.

  9. #9
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Not a spec -- a calling contract
    Interfaces are not suppose to just be a "calling contract", there is an implied semantics. The interfaces are purely syntactic...but when you implement an interface you are doing so with a particular semantics in mind. If the semantics are ignored then interfaces become useless...knowing some class has a "calculateShipping()" method is useless unless you know that the method actually does what is implied (i.e. the calculation of shipping). This is for the most part a "spec".

    The rest of your comment concerning PHP's implementation of interfaces wasn't clear to me. Can you clarify?
    PHP only has abstract classes. PHP's interfaces don't behave how you'd think interfaces would behave. Say you want to implement two interfaces but both of them have a method in common..in PHP you get an error.

  10. #10
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    As in the following for example, is what you mean?

    PHP Code:
    interface ExampleOne {
            public function 
    exampleOne();
        }
        
        interface 
    ExampleTwo {
            public function 
    exampleOne();
            public function 
    exampleTwo();
        }
        
        class 
    ConcreteExample implements ExampleOneExampleTwo {
            public function 
    __construct() {}
            public function 
    exampleOne() {}
            public function 
    exampleTwo() {}
        }
        
        
    $ex = new ConcreteExample();
        
    // reports [php5.1.1] Fatal error: Can't inherit abstract function ExampleTwo::exampleOne() (previously declared abstract in ExampleOne) in C:\ ... 
    I believe in Java you can do this provided that each declaration from the given Interfaces, they has different function arguments, but my memory may be failing me at the moment

  11. #11
    SitePoint Guru dbevfat's Avatar
    Join Date
    Dec 2004
    Location
    ljubljana, slovenia
    Posts
    684
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by binjured
    ...
    I'm not sure what "something()" or "unk(...)" may do, but I think it's conceivable that they could be of some kind of use Or, I guess the abstract function could be dropped all-together and just have one or more functions in the Comment class that use Commentable objects. ...
    I'd call this over-designing - putting methods in your code that you're not even sure you'd need

    Maybe you should take it easy and implement interfaces only when necessary, but not use them if your code is sufficiently satisfiable?

    @Snaily: the only thing that is "wrong" with interfaces in php is that you cannot declare a same method in two (or more) that are implemented in a single class (or extended into single interface). I'm not sure why this makes you feel there's no interfaces in php? This is what differs them from abstract classes:
    - only public methods, no body,
    - have a separate hierarchy than classes,
    - multiple inheritance of interfaces in an interface
    - multiple implementation of interfaces in a class.

    You can't possibly call these abstract classes, can you?

  12. #12
    SitePoint Addict
    Join Date
    Aug 2003
    Location
    Toronto
    Posts
    300
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Snaily
    Interfaces are not suppose to just be a "calling contract", there is an implied semantics. The interfaces are purely syntactic...but when you implement an interface you are doing so with a particular semantics in mind. If the semantics are ignored then interfaces become useless...knowing some class has a "calculateShipping()" method is useless unless you know that the method actually does what is implied (i.e. the calculation of shipping). This is for the most part a "spec".
    That sounds more like aspects to me. I certainly don't claim to be an expert in OOP interface theory but I'm not familiar with definitions of interfaces in OOP that differ from the calling contracts that I earlier suggested. I do agree that the methods of an interface should do what their names suggest, but again, I don't know of any typical OOP language that regulates that detail of contract (ie: at the semantic level). In the end, I don't think it is supposed to matter. If I have a render interface that includes a draw() method which I call, I surely expect that something will be "drawn" -- but how and where is not my concern since my duty as a user of the object was only to request the "draw" facility. If my concern was otherwise, I needn't be relying on an abstraction at the interface level, not? I assume that whatever draw() is supposed to do in that context will be done -- and that is enough for the caller to know; however, the fact that draw() can be called is important to know. The interface says what you can expect to call (the API) -- but it is up to the implementing class to define the behaviour of the call. I've always taken it as a given that in OOP concrete behaviour is supposed to be abstracted from the caller by the callee.

    Quote Originally Posted by Snaily
    PHP only has abstract classes. PHP's interfaces don't behave how you'd think interfaces would behave. Say you want to implement two interfaces but both of them have a method in common..in PHP you get an error.
    This is very true and I have no argument with that. I personally tend to use interfaces for rather specific purposes (mainly to ensure contracts in the manner that dbevfat's expounded on). Though I can imagine the situations where overlap could occur, I can't think of many situations where I would want to implement two interfaces that competed for a similar name. Rather, I would think to refactor the interfaces. Never-the-less, it is a valid point and concern. FWIW, mostly this issue seems to come up when multiple interfaces want to claim a very generic method name such as "execute". I suggest that such a name is so generalized as to carry little semantic meaning (at least in a cross-cutting context). Still, I don't claim to sweep that concern under the rug with that comment

    That said, I think that once again dbevfat's made astute comments in this regard -- certainly better than the ones I made here

    @Dr. L: as you fully know, PHP doesn't allow overloading of method signatures (in the explicit static sense), so a class couldn't implement two methods (from different interfaces) of the same name with different signatures in any case. As discussed, in PHP, you can't implement two interfaces that both shared a method with the same method name at any rate. IMO, neither of these would buy you a lot (in a practical sense).

    Greetings to all!
    Last edited by jayboots; Mar 3, 2006 at 03:56.

  13. #13
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by dreamscape
    Now sometimes I will implement an SPL interface; however, the SPL interfaces actually do something and change the behavior of the class in some way (ArrayAccess, Iterator, etc), something that to my knowledge you cannot do with your own interfaces since you can only define required methods.
    SPL (and other "built-in") interfaces are different. At the engine level they act like markers: if a class implements, say, "ArrayAccess", the engine just handle it differently, la:

    Code:
    offset_get:
       if object implements(ArrayAccess)
           call object's offset_get
       else
           call default offset_get

  14. #14
    SitePoint Addict
    Join Date
    Aug 2003
    Location
    Toronto
    Posts
    300
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by stereofrog
    SPL (and other "built-in") interfaces are different. At the engine level they act like markers: if a class implements, say, "ArrayAccess", the engine just handle it differently
    To expound of your idea, certain SPL interfaces act similarly to userland abstracts except that SPL (ie: engine level) interfaces participate in implements whereas userland abstracts can not. AFAIK, interfaces only exist to get around the notion (some might say limitation) of single inheritance while devices such as SPL interfaces blur the notion of single inheritance by providing concrete default behaviour -- without imposing dependancies on the userland class inheritance tree. Single inheritance is why SPL can not both be implemented in userland and remain easy " la PHP" to use. Fair?

  15. #15
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    > PHP doesn't allow overloading of method signatures (in the explicit static sense), so a class couldn't
    > implement two methods (from different interfaces) of the same name with different signatures in any
    > case.

    Well, yes I know that

    The point was though, I posted the example, just to make a comparison between what is possible (at the moment, as the object model may change...) and what isn't possible, that's all

  16. #16
    SitePoint Zealot DerelictMan's Avatar
    Join Date
    Oct 2005
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    I believe in Java you can do this provided that each declaration from the given Interfaces, they has different function arguments, but my memory may be failing me at the moment
    They arguments don't have to be different. The following is legal in Java:
    Code:
    public interface Foo {
        public void doSomething();
    }
    
    public interface Bar {
        public void doSomething();
    }
    
    public class Test implements Foo, Bar {
    
        public static void main(String[] args) {
            Test a = new Test();
            a.doSomething();
        }
    
        public void doSomething() {
            System.out.println("Hi there");
        }
    
    }
    FWIW...

  17. #17
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    but it is up to the implementing class to define the behaviour of the call. I've always taken it as a given that in OOP concrete behaviour is supposed to be abstracted from the caller by the callee.
    My point is although you can't write this into the interface explicitly there is always an implied "behavior"...the only thing that is left to the implementing classes is how exactly its done. Say for example the calculation of shipping, you may be accessing UPS to get shipping data...or maybe you have it stored locally. The behavior of the method is the same regardless.
    I believe in Java you can do this provided that each declaration from the given Interfaces, they has different function arguments, but my memory may be failing me at the moment
    They don't have to be different in java or any language that has real interfaces. This issue in PHP isn't that big of an issue. But when I first started playing with PHP5 I thought they'd be real interfaces and was suprised a few times by their behavior. If you think of them on the other hand as abstract classes there are no suprises.
    You can't possibly call these abstract classes, can you?
    Yes..the only difference is "purely abstract" classes in PHP can have multiple inheritance. Last time I looked under the hood in PHP they are implemented as a special abstract class.

  18. #18
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    United Kingdom
    Posts
    208
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The notion that Java can implement two interfaces with identical methods seems a little strange to me. Snaily you have talked about the implied behaviour of an interface - surely that implication is lost when two interfaces share identical methods.

    As an aside I have always wondered why method overloading isn't possible in PHP using the size of the argument list as the overloading point.

  19. #19
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The notion that Java can implement two interfaces with identical methods seems a little strange to me. Snaily you have talked about the implied behaviour of an interface - surely that implication is lost when two interfaces share identical methods.
    When I do this sort of thing in Java there are no issues with the "implied behavior" of the interface. It can be pretty useful for avoiding things like package cycles (doesn't apply to php much). Its also useful when you need to split up a big interface but can't because the sub-interfaces of the interface need to overlap. There are more things you can do with it...but I can't think of them at the moment.

  20. #20
    SitePoint Zealot DerelictMan's Avatar
    Join Date
    Oct 2005
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Shrike
    The notion that Java can implement two interfaces with identical methods seems a little strange to me.
    It doesn't to me personally, but that's because I really view interfaces in java from a very practical perspective: they are necessary in a strictly-typed language to allow the programmer to deal in a general fashion with a set of types from different class hierarchies that all respond to a defined set of messages. So, to me, it's about the messages the object can respond to, so I have no problem with a class that implements multiple interfaces that overlap. This is also the reason that I see interfaces (whether they are "real" or not) in PHP as being fairly pointless and silly, since PHP is dynamically typed and duck-typing is more than sufficient. I realize that this may not be a popular viewpoint around here , but nevertheless there it is.

    As an aside I have always wondered why method overloading isn't possible in PHP using the size of the argument list as the overloading point.
    I imagine the PHP devs might say this is a slippery slope... it could definitely be done, but if it were implemented then someone would want to overload based on type-hints (which would really require type-hinting for primitive types to be fully effective), and next thing you know PHP is getting closer and closer to a strictly typed language (or at least being able to be used that way). I imagine they would say that it doesn't follow the principle of so-called "extreme simplicity".

  21. #21
    simple tester McGruff's Avatar
    Join Date
    Sep 2003
    Location
    Glasgow
    Posts
    1,690
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Snaily
    there is always an implied "behavior"
    Not necessarily. This could do absolutely anything - indeed that's the whole point. A client controller can be configured with different handler sequences to carry out different jobs.
    PHP Code:
      /*
          Interface to be implemented by Gof chain handlers.
      */
      
    class Handler {
          function try() {
          }
      } 

  22. #22
    SitePoint Guru
    Join Date
    Feb 2006
    Location
    Pittsburgh, Los Angeles
    Posts
    706
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    in PHP as being fairly pointless and silly, since PHP is dynamically typed and duck-typing is more than sufficient.
    Yeah interfaces seem to only add value to languages that have static typing. Although in PHPs case I think they do add a little value to the readability of the code base though (the interface really just becomes some piece of documentation).
    Not necessarily. This could do absolutely anything - indeed that's the whole point. A client controller can be configured with different handler sequences to carry out different jobs.
    I fail to see how this lacks an implied behavior (i.e. semantic content).


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •