PHP:Concept of interfaces? [duplicate] - php

This question already has answers here:
What is the point of interfaces in PHP?
(15 answers)
Closed 9 years ago.
Can anybody explain the concept of interfaces with good example. I searched but didn't find a good answer. I'm still confused with these concepts.
I found an example for interface from Internet which is shown below. The code works without the interface with the same output. Then what is the purpose of it? Or is it not the real implementation of interfaces?. I need to move from procedural coding to object oriented programming. It would be better if anyone can explain not in more complex technical words.
<?php
interface IPillage
{
public function emptyBankAccounts();
public function burnDocuments();
}
class Employee
{
public function emptyBankAccounts()
{
echo "Call employees and ask to transfer funds to Swiss bank account";
}
public function burnDocuments()
{
echo "Torch the office suite of the employee";
}
}
class Executive extends Employee implements IPillage
{
public function emptyBankAccounts()
{
echo "Call executive and ask to transfer funds to Swiss bank account";
}
public function burnDocuments()
{
echo "Torch the office suite of the executive";
}
}
$obj1=new Employee();
$obj2=new Executive();
$obj1->emptyBankAccounts();
echo '<br>';
$obj2->emptyBankAccounts();
?>

many languages just allow single inheritance, with the interfaces, you are allow to have a kind of multiple inheritance... you can inherit from a base class and in the same time from many interfaces as well.
For example, you can have many classes like.. human, animal, truck. They are different of course, but they can implement an interface like "movable" with a method called "to move."
In that case i can refere to three differents objects from the optical of a "movable element'. I can say myHuman.move/ myMonkey.move / my Truck.move.. I am sure that I can ask for move to any object that implements the movable interface with out take care about another things that the particular objects can do... To think about an interface I have to think about funcionality that they offer.
Sorry about my english I am from Argentina.
Nicolas Perichon

Interface:
cannot be instantiated.is a special type of abstract class in which all the members do not have any implementations.
enables polymorphism.
A class can implement more than 1 Interfaces.
Normally used for application classes: providing contract for ensuring interactibility.
the aim: making sure something is interchangeable.
A class that implements an Interface need to contain all the implementation, otherwise the compiler will throw an error.
CAN-DO relationship.
e.g. Student CAN enrol, Student CAN submit assignment.
public interface ICanEnrol
{
void Enrol();
}
public interface ICanSubmit
{
void Submit();
}
public class Student : ICanEnrol, ICanSubmit
{
public void Enrol()
{
School.Send("enrolment");
}
public void Submit()
{
School.Send("report");
}
}
public class Employee : ICanEnrol, ICanSubmit
{
public void Enrol()
{
Company.Send("enrolment");
}
public void Submit()
{
Company.Send("report");
}
}

As PraDes wrote, creating an interface creates a sort of contract. That is really the key concept here.
Let's say that you are working on a project with a team of other developers. There are several new classes that need to be written and the team wants to come to a consensus on a common approach / design pattern. Everyone agrees that each of these classes will need a foo method, a bar method and a baz method. The concrete details of how these methods will work is going to be a little bit different in each class. However, they should each have the same signature.
We decide to create an interface which names the methods that each of these classes should have (foo, bar, baz) and what their signatures are (ie what params they take). Now when each of us writes one of these new classes we will "implement" the interface. By declaring that "MyClass" implements "MyInterface" we are now required to implement foo, bar, and baz methods in our class. If we do not, our IDE, our compiler, our runtime environment, etc will throw an error.

Related

Use of interface empty method and multiple inheritance to single normal class

As in interface only a method is specified without codes like
interface eat {
public function ways_of_eating_food($givingsomefood);
}
//and remaining class does is only access the method whats the use of it as they could manually create it in the class to
class human implements eat {
public function ways_of_eating_food($foodtoeat){
This is how people eat the food//
}
}
class animal implements eat {
public function ways_of_eating_food($foodtoeat){
//this is how animal eat the food
}
}
As animal and human are two difference class the core part are part are same that is they do eat food given but the style is different so what actually is this useful and how can interface supports multiple inheritance
Interfaces are useful for data hiding. Let's say you want to provide a class to some client code, but don't want to give them full access. One way to restrict access without limiting the functionality of your class is to implement an interface and require the client code to get objects through a factory.
Another benefit of interfaces is team development. If you have a dozen programmers working on different pieces of code that need to connect, it's best to define interfaces for the connections. As long as the programmers write according to the interfaces, everything will link together nicely regardless of personal choices and style.
Yet another benefit is that with interfaces you can use a class without having defined it first. For example, if you have a class that does a lot of intricate work and won't be finished before the rest of the project, the rest of the project can use an interface to it and avoid being stalled by the development of that one class.
Imagine you don`t really know what are the different ways living being can eat but you do not want other classes to not function before you discover all the possible eating methods. Just declare an interface eat and let other classes implement it.
source
 they do eat food given but the style is different so what actually is this useful
You should read about type-hints. Interfaces are useful to manage objects that share behaviors, but you don't know before runtime which object you will have to use.
Consider a function that makes beings eat. Since you make an interface, you can type hint the interface in the function so it can manage any kind of eating beings:
function makeEat(eat $obj) { $obj->ways_of_eating_food( getFood() ); }
function getFood() { return $food; }
If you had not defined an interface however, you would have to make a function to make humans eat, another one to make cats eat, another one to make dogs eat, etc. This is really impractical. By using an interface and type-hinting it to the function, you can use the same function to do the same job.
how can interface supports multiple inheritance
As commented by Vincent:
PHP does support Multi-level inheritance, not multiple inheritance.
This means you can implement multiple different interfaces, but not extend multiple classes.
interface living { public function eat(food $food); }
interface food { public function getEnergyValue(); }
interface animal { public function breath(); }
class cow implements living, animal
{
private $energy = 0;
private $secondsRemaining = 10;
public function eat(food $food) { $this->energy += $food->getEnergyValue(); }
public function breath() { $this->secondsRemaining += 10; }
}
class salad implements food
{
private $value = 50;
public function getEnergyValue() { return $this->value; }
}
$bob = new cow();
$bob->eat(new salad());

How to name my classes? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a base user class which is responsible for manipulating the basic user information: name, age, location, etc. I want to extend my system with the groups functionality and later with projects and meetings. For example:
class User
{
public function getName() {
...
}
public function getAge() {
...
}
}
And then extend it with groups functionality:
class GroupableUser extends User
{
public function join($groupId) {
...
}
public function leave($groupId) {
}
public function requestGroupInvitation($groupId) {
...
}
public function acceptGroupInvitation($groupId) {
...
}
}
The name GroupableUser seems weird to me, however it does't make sense to add join and leave methods to Group class, because its user that joins and leaves a group, not the other way around.
And later I would have classes like UserThatCanHaveProjects and UserThatCanParticipateInMeetings.
How to name these classes?
And how do you typically deal with these situations?
You can't seem to be able to find a way to name the classes because the hierarchy is not very natural. In reality a user may participate in more than one group and each group may have more than one user. But a user may exist without a group, while there can't be a group without a user. I would say this means users should be a member of a group and addUser and removeUser should be placed in Group. Why? Because a user may not even "know" that he may join or leave a group and be perfectly happy, while there can not be a group that does not "know" that a user may join it.
The capability to participate in groups/meetings and have projects is something that a user might be able to do, but it's not something that defines what a user is. This is a pretty clear sign that modelling these options with additional classes is not a good design choice.
Static approach #1: interfaces
In a statically typed language a simplistic implementation would look something like
interface IGrouppableUser {
public function join(...);
}
class GroupableUser implements IGrouppableUser {
public function join(...) { /* implementation */ }
}
And the consumers of grouppable users would accept IGrouppableUser, allowing you to craft as many classes as necessary. You can also do this in PHP, but as mentioned earlier it's probably not a good design no matter what the language.
As a footnote, I should add that with the addition of traits to the language starting from PHP 5.4 the above scenario can be implemented a bit more conveniently (classes can use a trait instead of implementing an interface, which means you don't need to copy/paste the implementation of join all around the code base). But conceptually it's the exact same approach.
The main disadvantage of this approach is that it does not scale. It might be OK if you only need two or three types of users.
Static approach #2: "not supported" exceptions
If most of the users are grouppable and can have projects then it doesn't make much sense to create a hellish hierarchy of classes; you can just add the necessary members to class User, making it a fat interface:
class GroupableUser implements IGrouppableUser {
private $isGrouppable = true; // default, can be changed at runtime
public function join(...) {
if (!$this->isGrouppable) throw new Exception("User is not grouppable!");
// real implementation
}
}
The main disadvantage of this approach is that it makes the class User appear to unconditionally support a wide range of operations when in fact it does not and as a result can make coding tedious and error-prone (lots of try/catch). It might be OK if the vast majority of users support the vast majority of operations.
Dynamic approach #1: behaviors
It would be much better to conditionally allow User instances to participate in these operations. This means that you need to be able to dynamically attach "behaviors" to User objects, which is fortunately quite easy to do in a dynamically typed language.
I suggest looking up a "behaviors" implementation from an established open-source project, but here's a quick and dirty example:
Behavior base class and sample implementation
abstract class Behavior {
public function provides($name) {
return method_exists($this, $name);
}
public function invoke($target, $name, $arguments) {
array_unshift($arguments, $target);
return call_user_func_array(array($this, $name), $arguments);
}
}
class GrouppableBehavior extends Behavior {
public function join(User $user, $groupName) {
echo "The user has joined group $groupName.";
}
}
Composable (can use behaviors) base class and User implementation
class Composable {
private $behaviors = array();
public function __call($name, $arguments) {
foreach ($this->behaviors as $behavior) {
if ($behavior->provides($name)) {
return $behavior->invoke($this, $name, $arguments);
}
}
throw new Exception("No method $name and no behavior that implements it");
}
public function attach($behavior) {
$this->behaviors[] = $behavior;
}
}
class User extends Composable {}
Test driver
$user1 = new User;
$user2 = new User;
$user1->attach(new GrouppableBehavior);
$user1->join('Test Group'); // works
$user2->join('Test Group'); // throws
See it in action.
The main disadvantages of this approach are that it consumes more runtime resources and that behaviors can only access public members of the classes they are attaching to. In some cases you may find yourself forced to expose an implementation detail that should be private to enable a behavior to work.
Dynamic approach #2: decorators
A variation on behaviors is the decorator pattern:
interface IUser {}
interface IGrouppableUser extends IUser {
public function join(...);
}
class User implements IUser {}
class UserGroupingDecorator implements IGrouppableUser {
private $realUser;
public function __construct(IUser $realUser) {
$this->realUser = $realUser;
}
public function join(...) { /* implementation */ }
/* now you need to implement all IUser methods
and forward the calls to $this->realUser */
/* if IUser exposes bare properties we have a problem! */
}
Using this pattern you can create a UserGroupingDecorator that wraps an IUser at will and pass the decorator to anything that accepts either an IUser or an IGrouppableUser.
The main disadvantage of this approach is that it also does not provide access to the non-public members of User. In addition it rules out exposing bare properties from IUser as there is no way to "forward" bare property accesses from UserGroupingDecorator to $realUser if the properties are also defined on the former -- and you cannot implement IGrouppableUser unless they are indeed defined. This state of affairs can be sidestepped by exposing properties as distinct getter/setter methods, but that means still more code to write.
Thinking in terms of a database-driven web app, I might do this with 5 classes:
1) User
2) Group
3) GroupAssignment
4) GroupInvitation
5) GroupInvitationRequest
Class 3 just maps one User to one Group. Classes 4 and 5 are even more obvious. This setup pretty much matches what you would have in a database anyway. This allows for a good amount of flexibility, as a User could be a member of many groups (or one, or none).
EDIT: Added additional classes based on new information in question.
Groupable would be a good name for interface, Interface should describe an aspect of class, that might be required by instance of some different class. Interfaces are contract between classes.
Just don't stick the "I" in front of it, unless you use hungarian notation for everything. Simply use nouns for class names and adjectives for interfaces.
As for the name of class, I would go with:
class Participant extends User implements Groupable
{
// methods that will be expected by from instance of this class
// by any class that requires an object to have Groupable interfrace
}

PHP Multiple Inheritance with Interfaces

I'm trying to understand how using interfaces gives me multiple inheritance as I've been googling.
class A
{
function do1(){}
function do2(){}
function do3(){}
}
class B extends A
{
function do4(){}
function do5(){}
function do6(){}
}
class C extends B
{
}
In the above example, class C has all the methods from class A and B. However, class B also has all the methods of class A, which is not necessary desired.
My searches have come up to use interfaces to solve this issue by moving methods to a class and creating interfaces, as below.
interface A
{
function do1();
function do2();
function do3();
}
interface B
{
function do4();
function do5();
function do6();
}
class C implements A, B
{
function do1(){}
function do2(){}
function do3(){}
function do4(){}
function do5(){}
function do6(){}
}
I don't really see how this solves the issue because all the code is in the new class. If I just wanted to use class A as originally, I would have to create a new class that implement interface A and copy the same code to the new class.
Is there something I'm missing?
PHP doesn't have multiple inheritance. If you have PHP 5.4, though, you can use traits to at least avoid every class having to copy code.
interface A {
public function do1();
public function do2();
public function do3();
}
trait Alike {
public function do1() { }
public function do2() { }
public function do3() { }
}
interface B {
public function do4();
public function do5();
public function do6();
}
trait Blike {
public function do4() { }
public function do5() { }
public function do6() { }
}
class C implements A, B {
use Alike, Blike;
}
class D implements A {
use Alike;
// You can even "override" methods defined in a trait
public function do2() { }
}
Note, though, you have to both implement the interface and use the trait (or, of course, provide your own implementation). And C and D are not related at all, except in both implementing the A interface. Traits are basically just interpreter-level copy and paste, and do not affect inheritance.
The first thing to understand about interfaces is that they are NOT used for inheritance. That is a very important thing to understand. If you're trying to make several classes share the same concrete code, that is not what an interface is for.
The second thing to understand is the difference between client code, and service code.
Client code is essentially the "last step" in a sequence of requests for data. A controller or a view in MVC can be considered client code. The model, meanwhile can be considered service code.
Interfaces are intended for client code to enforce consistency in the types of data it gets from services. Or another way to think about it - interfaces are a way for services to make sure they will be compatible with a request from client code. That is ALL they do. They quite literally provide an interface by which data is accessed, not an implementation that multiple classes can share.
So to give you a concrete example:
Client Code - a ProfileViewController class for a user's forum profile
class ProfileViewController
{
public function showProfile(User $user)
{
$user->getProfile();
}
}
Service Code - a User model that retrieves data and passes it on to the client code that is requesting it
class User
{
public function getProfile()
{
$profile = Do some SQL query here or something
return $profile;
}
}
Now suppose later on you decide to break up Users into Members, Administrators, Referees, Moderators, Writers, Editors etc, and that each has their own unique type of profile. (e.g. its own custom query, or data, or what have you)
There are now two problems present here:
You need to guarantee that whatever you pass in there will contain a getProfile() method.
showProfile() will fail if you pass in anything other than a User object.
1 is easy to solve through abstract classes and methods (or through Interfaces). 2 at first sounds easy as well, because you can just make Moderators, Admins, and Members all subclasses of a User base class.
But then what happens when down the road, in addition to USER profiles, you want to have generic profiles for things. Perhaps you want to show profiles of sports players, or even profiles of celebrities. They're not users, but they still have profiles/details pages.
Because they're not users, it may not make any sense to consider them subclasses of User.
So now you're a bit stuck. showProfile() needs to be able to accept more than just a User object. In fact, you don't know what type of object you will ultimately want to pass in there. But at the same time, since you always want to be able to grab $user->getProfile(), anything you pass in there must be generic enough to be passed in, AND implement a concrete getProfile() method.
Solution? Interfaces!!!!!
First some service code
// First define an interface for ANY service object that will have a profile
interface IHasProfile
{
public function getProfile();
}
// Next, define the class for an object that should have a profile. I'll do a bunch for the sake of an example...
class User implements IHasProfile
{
public function getProfile()
{
$profile = Your unique user profile query here
return $profile;
}
}
class Celebrity implements IHasProfile
{
public function getProfile()
{
$profile = Your unique celebrity profile query here
return $profile;
}
}
class Car implements IHasProfile
{
public function getProfile()
{
$profile = Your unique vehicle profile query goes here
return $profile;
}
}
Next, the client code that will use it
class ProfileViewController
{
public function showProfile(IHasProfile $obj)
{
$obj->getProfile();
}
}
And there you have it. showProfile() has now been abstracted enough that it doesn't care what object it gets, it only cares that the object has a public getProfile() method. So now you can create new types of objects to your heart's content, and if they are intended to have profiles, you can just give them "implements IHasProfile" and they will automatically just work with showProfile().
Kind of a contrived example, but it should illustrate at least the concept of interfaces.
Of course, you could just be "lazy" and not typecast the object at all, and thus allowing ANY object to be passed in. But that's a separate topic entirely ;)
Multiple inheritance is possible only for Interfaces!
such as my output for it:
php > interface A{};
php > interface B{};
php > interface C extends A,B{};
php > class D implements C{};
php > $d = new D();
php > echo ($d instanceof A);
1
I created A and B interfaces and C interface extends them.
After we have D class which implements C interface
Finally, I ask if $d object is instanceof A interface, yeah it's true
For the lulz, I try to create E class which extends D and stdclass classes and get error!
php > class E extends D, stdclass{};
PHP Parse error: syntax error, unexpected ',', expecting '{' in php shell code on line 1
Parse error: syntax error, unexpected ',', expecting '{' in php shell code on line 1
Multiple inheritance is not possible in PHP like in many OOP supported languages
See similar topic here. The topic is in AS3 but gives you answer.
To answer particularly about solving using interfaces is answered in the same post here
As told here by #tonicospinelli, it seems that indeed, PHP allows multiple inheritance of interfaces, but it isn't clearly explained, just given an example
The way multiple inheritance works, PHP passes these using Traits that implement Interfaces.
Once you declare a Class implementing a "multi-interface" (1), you may use already defined Traits to assure inheritance is well-performed.
(1): Saying "multi-interface" I mean a class implementing an interface what extends from multiple other interfaces

Implementing an interface with different types

I would like to have an interface that allows for a generic type
public function persist($object);
But my concrete implementations to have a type
public function persist(User $user);
From what I understand of PHP this is not possible. From an object oriented design point of view could someone explain to me why what I am doing is misguided and wrong.
Edit: I should clarify, I'm aware of type hinting and how it works my question is really trying to understand from an OO perspective where I am going wrong when I want my concrete implementation to take a different type to the interface.
The interface's purpose is to be a contract between classes. An interface would be useless if multiple concrete classes implemented it, but all expected different inputs. By looking at the interface, you would not know what type of inputs that the implementing classes expect, thus making the interface basically useless. You could not interchange different concrete classes that all use the same interface, as they all expect different inputs (have different interfaces).
I could not replace classA with classB with the assurance that they would both work, since they both have the same interface. This would basically make interfaces useless for every OOP pattern known to man.
EDIT EXAMPLE
class CommandList {
public function addCommand(Command $command) {
$this->commands[] = $command;
}
public function runCommands() {
foreach ($this->commands as $command) $command->run($this);
}
}
interface Command {
public function run(CommandList $commandList);
}
class Hop implements Command {
public function run(CommandList $commandList) {
// hop here
}
}
class Skip implements Command {
public function run(CommandList $commandList) {
// skip here
}
}
See how the interface acts as a contract? If you break that contact, then things that implement Command would not be interchangeable.

How to work with PHP abstract?

Why would you use such abstract? Does it speed up work or what exactly its for?
// file1.php
abstract class Search_Adapter_Abstract {
private $ch = null;
abstract private function __construct()
{
}
abstract public funciton __destruct() {
curl_close($this->ch);
}
abstract public function search($searchString,$offset,$count);
}
// file2.php
include("file1.php");
class abc extends Search_Adapter_Abstract
{
// Will the curl_close now automatically be closed?
}
What is the reason of extending abstract here? Makes me confused. What can i get from it now?
You can use abstract classes to define and partially implement common tasks that an extended class should do. Since explaining it is difficult without an example, consider this:
Without abstract classes, you would have to define two basic classes with the same methods and implementation. Since OOP is all about preventing code duplication, this is quite wrong:
class Car {
public $brand = 'mercedes';
public function gasPerMile($weight)
{
// Useless calculation, purely for illustrating
$foo = $weight * 89 / 100;
return $foo;
}
public function carSpecificFunction()
{
// Only present in class Car
}
}
class Truck {
public $brand = 'MAN';
public function gasPerMile($weight)
{
// Useless calculation, purely for illustrating
$foo = $weight * 89 / 100;
return $foo;
}
public function truckSpecificFunction()
{
// Only present in class Truck
}
}
Now you have some common properties and methods, which are duplicated in two classes. To prevent that, we could define an abstract class from which Car and Truck are extended. This way, common functionalities are kept in one place and the extended classes will implement specific properties and methods for either the Truck or the Car.
abstract class Vehicle {
abstract public $brand;
public function gasPerMile($weight)
{
// Useless calculation, purely for illustrating
$foo = $weight * 89 / 100;
return $foo;
}
}
This way, you ensure that atleast every class that extends Vehicle has to have a brand specified and the common gasPerMile() method can be used by all extended classes.
Of course, this is a simple example, but hopefully it illustrates why abstract classes can be useful.
So you can implement different Search adapters and all of them must implement that search method. See inheritance here.
Basically what you get is that every class extending "Search_Adapter_Abstract" can be used as a Search Adapter. The behaviour changes (because the method search is implementend differently) but you guarantee the "search" method is there with that signature.
This isn't going to be a popular answer, but still...
abstract, interface, private and other keywords, borrowed from Java, are elements of cargo cult programming and serve no real purpose in PHP, except to make the author appear more "serious" and "professional".
Explanation: these keywords are compile-time contracts, that have no effect on how your program runs and only meant as an aid for a compiler... assuming you have one. In a compiled language, like Java or C#, you physically cannot deploy a program that violates a contract, e.g. doesn't implement an abstract method. You simply don't get it compiled. This is a Good Thing, because you can fix some kinds of bugs very quickly, without testing and debugging.
PHP, on the contrary, doesn't have a compiler, and performs all contract checks at run time. This is a Bad Thing, because you need to test and debug to find contract violations manually. Consider the following:
class Abs {
abstract function implementMe();
}
if ($_GET['x'] == 'foo')
include "GoodClass.php";
if ($_GET['x'] == 'bar')
include "BadClass.php";
where "BadClass" extends "Abs", but doesn't implement "implementMe" method. This script can be deployed and will run just fine until someone calls it with "?x=bar" and then - bang! - your program suddenly crashes. To make the things worse, this will be a "fatal" error, so that you won't be even able to handle it in a reasonable way.
That is, abstract and friends are not only useless, but also quite harmful in PHP. Not only they don't help you with bug hunting, but also they are potential source of even more glitches. Stay away.

Categories