PHP Interfaces: How are they usable in practice? - php

I'll start by saying that I know how PHP interfaces work and how to "use" them.
My question is rather; how do they become useful in real life applications?
I've been writing PHP for over 3 years now and have never felt the need for an interface. I am writing interfaces more for good practice than for a particular purpose.

I'll provide an example where I've used interfaces in my own real-world experience.
Interfaces are extremely useful when you need to define something like a plugin architecture. Suppose your application accepts authentication plugins, allowing your end user implementers to integrate with their own internal auth infrastructures (LDAP, Shibboleth, some custom auth database, whatever). In order for a plugin to be compatible, it must implement the following methods:
validate_user()
start_user_session()
logout_user()
get_user_details()
If defined in an interface, a class then implements the interface ensuring that the necessary methods are present for compatibility with the plugin architecture.
Unfortunately, PHP does not enforce the return type of interface methods, so you must simply take care to document the expected return functionality of your methods.

They are not so useful - yet. Their main purpose seems to be for type hinting. When you write two separate classes that implement the same interface, you can use that interface in the type hint for a function. That way, you know you got all the methods of that interface available in the object that is passed in the parameter.
Unfortunately, PHP doesn't actually check if any called methods or properties you call on that parameter are actually in that interface, so you can accidentally use an object property that is not available in the interface, causing potential bugs when an object of a different type is passed.
Other languages are much stricter in this situation and will only allow you to use only that functionality that is declared in the interface.
Nevertheless, they are convenient for this purpose in PHP too, and maybe these checks will become stricter in future versions, so it becomes less error prone.

Check out the Standard PHP Library (SPL)
http://php.net/manual/en/book.spl.php
Countable and RecursiveIterator might give you a clue.

Related

How should I make my classes interact

I've been writing PHP within WordPress for a while, but I'm pretty new to straight PHP applications. I'm writing a little application that uses a few different APIs to do cross posting.
I've written the classes, but I'm not sure of the best way to have them interact.
A bit of background on the classes and their functionality. I've got a class for each API (Reddit, Imgur, Twitter), a class with some Curl helper functions, a class that carries out the process. I don't think I'll ever need more than one instance of any of these current classes. Nor will they ever need to be extended.
From what I've read, I've got a few options:
Instantiate each class as a global variable (I've heard I should avoid this)
Make the classes singletons (Also heard I maybe should avoid this)
Static methods - though some of the classes need to be instantiated and I'm not sure how that would work.
Those are the methods I've heard of. I'm expecting the answer will be none of the above. How do frameworks like Laravel do this?
This might be subjective, but I'm sure I'll learn something about patterns.
Edit: I probably should add some examples of the types of interactions required.
An API class using the CurlHelper class (I'm currently using a static method: $post_string = CurlHelper::createPostString( $post_data );)
Generating a title in one class for use when cross posting to each API

When to use Interfaces in PHP

I have always had a hard time understanding the real value of Interfaces when coding with Objects in PHP (could be other languages I imagine)
From what I understand you use an Interface to enforce or guarantee that when a Class is using an Interface that that class will have the methods defined in the Interface inside of that class.
So from my litte knowledge of using them, wouldn't that mean you would only find an Interface beneficial when defining more then 1 class that needs those Methods?
To be more clear, if I have a class that does one thing and no other classes need to do that kind of thing, then it would be pointless to use an Interface on that class?
So you wouldn't use an Interface on EVERY class you right?
PS) If you vote this question as exact duplicate then you didn't read the question and only the title as I have read most of the similar questions already
From what I understand you use an Interface to enforce or guarantee
that when a Class is using an Interface that that class will have the
methods defined in the Interface inside of that class.
This is actually only half of the deal (the technical part). There's also the all-important architectural half, which appears when you consume the interface and it goes like this:
function feed(IAnimal $interface) {
// ...
}
(alternatively, a "factory" function that is documented to return an instance that implements IAnimal would also serve as an example).
The idea here is that the consumer of the interface says: "I want an animal to feed. I don't care if it flies, walks, or crawls. I don't care if it's big or small. I only care that it shares some features with all other animals" -- features that would comprise the definition of the interface.
In other words, interfaces serve to abstract the contract (interface) from the concrete implementation (classes). This gives implementers of concrete classes a free hand to modify, rename, remove and add implementations without breaking the code for users of the interface, something that is not possible if you are referencing concrete classes directly in your API.
As for the interface that is implemented by one class only: that's not enough information to decide. If there can plausibly be more implementations of the interface in the future, then it certainly does make sense (for example: an IHashFunction interface would make sense even if Sha1HashFunction were currently the only available implementation). Otherwise it doesn't offer anything.

Why should I create Interfaces in PHP? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the point of interfaces in PHP?
Why should I create Interfaces in PHP?
As I understands, interfaces are there to describe classes that implement them. The classes have to contain at least these functions. This is all fine if you're building upon someone else's work, or have to maintain a degree of compatibility. But in more simplistic cases?
I know, that for the compiled programming languages, like C++, usage of interfaces allows for an increase in compiling speed, but what about PHP? This advantage seems to disappear, since PHP is interpreted, rather than compiled.
Interfaces are a way of 'emulating' multiple inheritance. A class in PHP can extend only one parent class, but can implement any number of interfaces, thus allowing you to create objects having many different types.
Perhaps a real world example will help to illustrate this. Imagine you need to build a series of logging classes that record messages to various media such as a text file, XML or a database. Each class needs to have separate code to interact with the different types of storage of course. However if they all implement the same interface the 'public face' that they show to other code is always the same. In that way other code that uses logging objects doesn't need to know what class they are instances of or what the storage medium is. All that they need to know is that all of the logging classes, by virtue of the fact that they all implement the same interface, share a common API. This can be a very powerful way of working. You can build up a library of code that solves related problems in different ways and simply 'plug and play' these in your code.
Interfaces are used to extend/emulate core PHP behavior, like iterators, array access, etc. This is the major thing that interfaces give you... that is, you cannot do it any other way.
You can also use interfaces to enforce parameter checks:
function foo(MyInterface $obj)
{
}
While not as useful as compile time checks that you would gain in another language (e.g., C++), the run time check can still be very useful in minimizing bugs.
Finally, interfaces can simplify some logic by using the is_a function or instanceof operator. You can just check if the "abstract" object implements a certain interface, and then do something accordingly.
The usage of interfaces has nothing to do with speed and will never will.
But it has a lot to do with decoupling and abstractization.
You will use them in PHP:
To hide implementation - establish an access protocol to a class of objects an change the underlying implementation without refactoring in all the places you've used that objects
To check type - as in making sure that a parameter has a specific type $object instanceof MyInterface
To enforce parameter checking at runtime - see #konforce answer
To implement multiple behaviours into a single class (build complex types)
class Car implements EngineInterface, BodyInterface, SteeringInterface {
so that a Car object ca now start(), stop() (EngineInterface) or goRight(),goLeft() (Steering interface)
and other things I cannot think off right now
From Thinking in Java:
An interface says, “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods might be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes.

why interfaces in dynamic/loosely-typed languages?

I work in php, and the concept of interfaces seems to me a little useless here. From reading, I understand that interfaces are part of "design by contract", but without at least guaranteeing a return of a type of a particular kind, there really isn't any contract. It seems it's like a contract that reads, "We agree to do the following: '' " -- there are no terms of the agreement.
If I want a guarantee that an object has a method, it doesn't seem like interfaces are particularly useful. If I try to call a method that an object doesn't have, I get a Fatal Error, so I find out pretty quickly that that class doesn't have a method with that name. If I want to be smart and check beforehand whether a class has a method, then checking the interface, and seeing whether the object implements that interface doesn't seem to save me any more time than just checking that object directly ( which I would do anyways to see if the class had that method regardless of any interfaces it did or didn't implement).
In other words, just because I have a set of methods that have particular names, that doesn't guarantee me any particular behavior. If I'm guaranteed a return of a variable of a certain type, I at least have some inkling of what the output would be, and I can write code that uses an object with that interface, because I know what I'm getting out of it. If it returns a string, I can continue coding with at least the certainty that I'm dealing with a string output afterward. So I'm guaranteed at least some behavior when a return type is specified. Is guaranteeing behavior part of what interfaces are for, or no?
The only thing I can think of is that when I'm writing code, it serves as a post-it note to myself to be sure to create certain methods when writing that class later on. It seems more like scaffolding for when I'm writing the code; I don't see much benefit from when I'm actually using it. So it's more for me to keep the standard when I'm creating classes than when I'm writing them. This benefit doesn't really seem to be captured in the concept of design by contract.
What benefit(s) do you actually get from using an interface in dynamic/loose-typed languages like PHP? Are they great, or is it something that more robust OO languages implement, so PHP implements it also?
Interfaces are used when you actually expect an object to implement a method.
For example, if I'm building a DB wrapper and it supports behaviours, which you register yourself in a bootstrap, then before running your behaviours (for example, sluggable), I will check that they implement my "DB_Wrapper_Behaviour_Interface" by using:
if(!($behaviourObject instanceof DB_Wrapper_Behaviour_Interface)) {
throw new Exception("Your behaviour doesn't implement my interface");
}
Design by contract is made more difficult without return types, but don't forget to favour 'tell' over 'ask'.
I believe an interface to be something like a responsibility. You are coding and need a collaborator. You ask it to do something because the code you are working on can't do everything. So you're asking another object to do something. An interface guarantees that the collaborator will do the job, but hides the 'how' it's done part.
Now you could argue that there's no need for the formal contract here, since the system will throw an error anyway if the collaborator can't do what you're asking it to do. But I think that misses the point in using interfaces as a responsibility.
Getting a fatal error is not always "easy". Sometimes you have to go on a specific module/action to see that something is actually missing in your class.
The interface enables you to make sure every method is implemented and to document these method (what the parameters are exactly going to be, what the return values should look like). This is useful if the parameters/values are arrays with a particular structure and you don't want to use classes instead (for the sake of simplicty).
I want to note, that PHP 5.4 will support type hinting. Right now I think there is only type hinting for function arguments, but I suppose there will be for return values, too. (At least there already is an RFC, though a very old and outdated one.)

Why should I use classes rather than just a collection of functions? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What are the benefits of OO programming? Will it help me write better code?
OO PHP Explanation for a braindead n00b
Just started learning/playing with creating classes in PHP and I'm wondering what pain do they solve? It seems like I can get the same job done with just a collection of functions that I include into the file. So my question is: Why should I use classes?
The Three Pillars of Object Oriented Programming. Learn them well:
http://codeidol.com/csharp/learncsharp2/Object-Oriented-Programming/The-Three-Pillars-of-Object-Oriented-Programming/
Encapsulation
The first pillar of object-oriented programming is encapsulation. The idea behind encapsulation is that you want to keep each type or class discreet and self-contained, so that you can change the implementation of one class without affecting any other class.
Specialization
The second pillar of object-oriented programming , specialization , is implemented through inheritance ; specifically by declaring that a new class derives from an existing class. The specialized class inherits the characteristics of the more general class. The specialized class is called a derived class, while the more general class is known as a base class.
Rather than cutting and pasting code from one type to another, the derived type inherits the shared fields and methods. If you change how a shared ability is implemented in the base class, you do not have to update code in every derived type; they inherit the changes.
Polymorphism
Polymorphism allows values of different data types to be handled using a uniform interface. The primary usage of polymorphism is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time
See also:
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
http://en.wikipedia.org/wiki/Type_polymorphism
It's a way to view your code in a more intuitive, real-world way. (You package the data and all possible operations on that data together.) It also encourages encapsulation, abstraction, data hiding... What you're really looking for is the advantages of OOP.
Basically, classes allow you to put your data with the code - i.e. organization.
Also, classes allow your "followers" to customize your classes without rewriting your code, but rather creating new inherited classes.
Every class-based code might be rewritten with functions, but it would be much harder to understand.
Generally, its so that you can customize the behavior of that set of functions. Typically you have a bunch of functions that work in concert.
People who use these functions may want to only modify one of them for some special case. Or maybe you provide a class that forces the functions to interact in a certain why, but you can't define what they'll actually do.
A trite example: imagine if you had some library to check that some things didn't overlap.
class Comparator:
def Greater(self, left, right): pass
def Less(self, left, right): pass
def EnforceNoOverlap(self, comparator, left, right)
assert comparator.Greater(left, right) != comparator.Lesser(left, right)
It a way to make your code more granular, with proper data hiding, separation of concerns and some other best practices.
IMO using only functions in your code sooner or later leads to spaghetti-code that is hard to maintain and extend. It's harder to fix bugs, its harder to implement new features, because often there are lots of code replication.
Also you can't use polymorphism in your code design, so you can't work with abstractions.
the classes/object is the way of implementation object-oriented application design. it covered detailed in numerous OOAD/OOP books.

Categories