Traits vs. interfaces - php

I've been trying to study up on PHP lately, and I find myself getting hung up on traits. I understand the concept of horizontal code reuse and not wanting to necessarily inherit from an abstract class. What I don't understand is: What is the crucial difference between using traits versus interfaces?
I've tried searching for a decent blog post or article explaining when to use one or the other, but the examples I've found so far seem so similar as to be identical.

Public Service Announcement:
I want to state for the record that I believe traits are almost always a code smell and should be avoided in favor of composition. It's my opinion that single inheritance is frequently abused to the point of being an anti-pattern and multiple inheritance only compounds this problem. You'll be much better served in most cases by favoring composition over inheritance (be it single or multiple). If you're still interested in traits and their relationship to interfaces, read on ...
Let's start by saying this:
Object-Oriented Programming (OOP) can be a difficult paradigm to grasp.
Just because you're using classes doesn't mean your code is
Object-Oriented (OO).
To write OO code you need to understand that OOP is really about the capabilities of your objects. You've got to think about classes in terms of what they can do instead of what they actually do. This is in stark contrast to traditional procedural programming where the focus is on making a bit of code "do something."
If OOP code is about planning and design, an interface is the blueprint and an object is the fully constructed house. Meanwhile, traits are simply a way to help build the house laid out by the blueprint (the interface).
Interfaces
So, why should we use interfaces? Quite simply, interfaces make our code less brittle. If you doubt this statement, ask anyone who's been forced to maintain legacy code that wasn't written against interfaces.
The interface is a contract between the programmer and his/her code. The interface says, "As long as you play by my rules you can implement me however you like and I promise I won't break your other code."
So as an example, consider a real-world scenario (no cars or widgets):
You want to implement a caching system for a web application to cut
down on server load
You start out by writing a class to cache request responses using APC:
class ApcCacher
{
public function fetch($key) {
return apc_fetch($key);
}
public function store($key, $data) {
return apc_store($key, $data);
}
public function delete($key) {
return apc_delete($key);
}
}
Then, in your HTTP response object, you check for a cache hit before doing all the work to generate the actual response:
class Controller
{
protected $req;
protected $resp;
protected $cacher;
public function __construct(Request $req, Response $resp, ApcCacher $cacher=NULL) {
$this->req = $req;
$this->resp = $resp;
$this->cacher = $cacher;
$this->buildResponse();
}
public function buildResponse() {
if (NULL !== $this->cacher && $response = $this->cacher->fetch($this->req->uri()) {
$this->resp = $response;
} else {
// Build the response manually
}
}
public function getResponse() {
return $this->resp;
}
}
This approach works great. But maybe a few weeks later you decide you want to use a file-based cache system instead of APC. Now you have to change your controller code because you've programmed your controller to work with the functionality of the ApcCacher class rather than to an interface that expresses the capabilities of the ApcCacher class. Let's say instead of the above you had made the Controller class reliant on a CacherInterface instead of the concrete ApcCacher like so:
// Your controller's constructor using the interface as a dependency
public function __construct(Request $req, Response $resp, CacherInterface $cacher=NULL)
To go along with that you define your interface like so:
interface CacherInterface
{
public function fetch($key);
public function store($key, $data);
public function delete($key);
}
In turn you have both your ApcCacher and your new FileCacher classes implement the CacherInterface and you program your Controller class to use the capabilities required by the interface.
This example (hopefully) demonstrates how programming to an interface allows you to change the internal implementation of your classes without worrying if the changes will break your other code.
Traits
Traits, on the other hand, are simply a method for re-using code. Interfaces should not be thought of as a mutually exclusive alternative to traits. In fact, creating traits that fulfill the capabilities required by an interface is the ideal use case.
You should only use traits when multiple classes share the same functionality (likely dictated by the same interface). There's no sense in using a trait to provide functionality for a single class: that only obfuscates what the class does and a better design would move the trait's functionality into the relevant class.
Consider the following trait implementation:
interface Person
{
public function greet();
public function eat($food);
}
trait EatingTrait
{
public function eat($food)
{
$this->putInMouth($food);
}
private function putInMouth($food)
{
// Digest delicious food
}
}
class NicePerson implements Person
{
use EatingTrait;
public function greet()
{
echo 'Good day, good sir!';
}
}
class MeanPerson implements Person
{
use EatingTrait;
public function greet()
{
echo 'Your mother was a hamster!';
}
}
A more concrete example: imagine both your FileCacher and your ApcCacher from the interface discussion use the same method to determine whether a cache entry is stale and should be deleted (obviously this isn't the case in real life, but go with it). You could write a trait and allow both classes to use it to for the common interface requirement.
One final word of caution: be careful not to go overboard with traits. Often traits are used as a crutch for poor design when unique class implementations would suffice. You should limit traits to fulfilling interface requirements for best code design.

An interface defines a set of methods that the implementing class must implement.
When a trait is use'd the implementations of the methods come along too--which doesn't happen in an Interface.
That is the biggest difference.
From the Horizontal Reuse for PHP RFC:
Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

A trait is essentially PHP's implementation of a mixin, and is effectively a set of extension methods which can be added to any class through the addition of the trait. The methods then become part of that class' implementation, but without using inheritance.
From the PHP Manual (emphasis mine):
Traits are a mechanism for code reuse in single inheritance languages such as PHP. ... It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.
An example:
trait myTrait {
function foo() { return "Foo!"; }
function bar() { return "Bar!"; }
}
With the above trait defined, I can now do the following:
class MyClass extends SomeBaseClass {
use myTrait; // Inclusion of the trait myTrait
}
At this point, when I create an instance of class MyClass, it has two methods, called foo() and bar() - which come from myTrait. And - notice that the trait-defined methods already have a method body - which an Interface-defined method can't.
Additionally - PHP, like many other languages, uses a single inheritance model - meaning that a class can derive from multiple interfaces, but not multiple classes. However, a PHP class can have multiple trait inclusions - which allows the programmer to include reusable pieces - as they might if including multiple base classes.
A few things to note:
-----------------------------------------------
| Interface | Base Class | Trait |
===============================================
> 1 per class | Yes | No | Yes |
---------------------------------------------------------------------
Define Method Body | No | Yes | Yes |
---------------------------------------------------------------------
Polymorphism | Yes | Yes | No |
---------------------------------------------------------------------
Polymorphism:
In the earlier example, where MyClass extends SomeBaseClass, MyClass is an instance of SomeBaseClass. In other words, an array such as SomeBaseClass[] bases can contain instances of MyClass. Similarly, if MyClass extended IBaseInterface, an array of IBaseInterface[] bases could contain instances of MyClass. There is no such polymorphic construct available with a trait - because a trait is essentially just code which is copied for the programmer's convenience into each class which uses it.
Precedence:
As described in the Manual:
An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in return override inherited methods.
So - consider the following scenario:
class BaseClass {
function SomeMethod() { /* Do stuff here */ }
}
interface IBase {
function SomeMethod();
}
trait myTrait {
function SomeMethod() { /* Do different stuff here */ }
}
class MyClass extends BaseClass implements IBase {
use myTrait;
function SomeMethod() { /* Do a third thing */ }
}
When creating an instance of MyClass, above, the following occurs:
The Interface IBase requires a parameterless function called SomeMethod() to be provided.
The base class BaseClass provides an implementation of this method - satisfying the need.
The trait myTrait provides a parameterless function called SomeMethod() as well, which takes precedence over the BaseClass-version
The class MyClass provides its own version of SomeMethod() - which takes precedence over the trait-version.
Conclusion
An Interface can not provide a default implementation of a method body, while a trait can.
An Interface is a polymorphic, inherited construct - while a trait is not.
Multiple Interfaces can be used in the same class, and so can multiple traits.

I think traits are useful to create classes that contain methods that can be used as methods of several different classes.
For example:
trait ToolKit
{
public $errors = array();
public function error($msg)
{
$this->errors[] = $msg;
return false;
}
}
You can have and use this "error" method in any class that uses this trait.
class Something
{
use Toolkit;
public function do_something($zipcode)
{
if (preg_match('/^[0-9]{5}$/', $zipcode) !== 1)
return $this->error('Invalid zipcode.');
// do something here
}
}
While with interfaces you can only declare the method signature, but not its functions' code. Also, to use an interface you need to follow a hierarchy, using implements. This is not the case with traits.
It is completely different!

For beginners above answer might be difficult, this is the easiest way to understand it:
Traits
trait SayWorld {
public function sayHello() {
echo 'World!';
}
}
so if you want to have sayHello function in other classes without re-creating the whole function you can use traits,
class MyClass{
use SayWorld;
}
$o = new MyClass();
$o->sayHello();
Cool right!
Not only functions you can use anything in the trait(function, variables, const...). Also, you can use multiple traits: use SayWorld, AnotherTraits;
Interface
interface SayWorld {
public function sayHello();
}
class MyClass implements SayWorld {
public function sayHello() {
echo 'World!';
}
}
So this is how interfaces differ from traits: You have to re-create everything in the interface in an implemented class. Interfaces don't have an implementation and interfaces can only have functions and constants, it cannot have variables.
I hope this helps!

Traits are simply for code reuse.
Interface just provides the signature of the functions that is to be defined in the class where it can be used depending on the programmer's discretion. Thus giving us a prototype for a group of classes.
For reference-
http://www.php.net/manual/en/language.oop5.traits.php

An often-used metaphor to describe Traits is Traits are interfaces with implementation.
This is a good way of thinking about it in most circumstances, but there are a number of subtle differences between the two.
For a start, the instanceof operator will not work with traits (ie, a trait is not a real object), therefore you can't use that to see if a class has a certain trait (or to see if two otherwise unrelated classes share a trait). That's what they mean by it being a construct for horizontal code re-use.
There are functions now in PHP that will let you get a list of all the traits a class uses, but trait-inheritance means you'll need to do recursive checks to reliably check if a class at some point has a specific trait (there's example code on the PHP doco pages). But yeah, it's certainly not as simple and clean as instanceof is, and IMHO it's a feature that would make PHP better.
Also, abstract classes are still classes, so they don't solve multiple-inheritance related code re-use problems. Remember you can only extend one class (real or abstract) but implement multiple interfaces.
I've found traits and interfaces are really good to use hand in hand to create pseudo multiple inheritance. Eg:
class SlidingDoor extends Door implements IKeyed
{
use KeyedTrait;
[...] // Generally not a lot else goes here since it's all in the trait
}
Doing this means you can use instanceof to determine if the particular Door object is Keyed or not, you know you'll get a consistent set of methods, etc, and all the code is in one place across all the classes that use the KeyedTrait.

You can consider a trait as an automated "copy-paste" of code, basically.
Using traits is dangerous since there is no mean to know what it does before execution.
However, traits are more flexible because of their lack of limitations such as inheritance.
Traits can be useful to inject a method which checks something into a class, for example, the existence of another method or attribute. A nice article on that (but in French, sorry).
For French-reading people who can get it, the GNU/Linux Magazine HS 54 has an article on this subject.

If you know English and know what trait means, it is exactly what the name says. It is a class-less pack of methods and properties you attach to existing classes by typing use.
Basically, you could compare it to a single variable. Closures functions can use these variables from outside of the scope and that way they have the value inside. They are powerful and can be used in everything. Same happens to traits if they are being used.

Other answers did a great job of explaining differences between interfaces and traits. I will focus on a useful real world example, in particular one which demonstrates that traits can use instance variables - allowing you add behavior to a class with minimal boilerplate code.
Again, like mentioned by others, traits pair well with interfaces, allowing the interface to specify the behavior contract, and the trait to fulfill the implementation.
Adding event publish / subscribe capabilities to a class can be a common scenario in some code bases. There's 3 common solutions:
Define a base class with event pub/sub code, and then classes which want to offer events can extend it in order to gain the capabilities.
Define a class with event pub/sub code, and then other classes which want to offer events can use it via composition, defining their own methods to wrap the composed object, proxying the method calls to it.
Define a trait with event pub/sub code, and then other classes which want to offer events can use the trait, aka import it, to gain the capabilities.
How well does each work?
#1 Doesn't work well. It would, until the day you realize you can't extend the base class because you're already extending something else. I won't show an example of this because it should be obvious how limiting it is to use inheritance like this.
#2 & #3 both work well. I'll show an example which highlights some differences.
First, some code that will be the same between both examples:
An interface
interface Observable {
function addEventListener($eventName, callable $listener);
function removeEventListener($eventName, callable $listener);
function removeAllEventListeners($eventName);
}
And some code to demonstrate usage:
$auction = new Auction();
// Add a listener, so we know when we get a bid.
$auction->addEventListener('bid', function($bidderName, $bidAmount){
echo "Got a bid of $bidAmount from $bidderName\n";
});
// Mock some bids.
foreach (['Moe', 'Curly', 'Larry'] as $name) {
$auction->addBid($name, rand());
}
Ok, now lets show how the implementation of the Auction class will differ when using traits.
First, here's how #2 (using composition) would look like:
class EventEmitter {
private $eventListenersByName = [];
function addEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName][] = $listener;
}
function removeEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName] = array_filter($this->eventListenersByName[$eventName], function($existingListener) use ($listener) {
return $existingListener === $listener;
});
}
function removeAllEventListeners($eventName) {
$this->eventListenersByName[$eventName] = [];
}
function triggerEvent($eventName, array $eventArgs) {
foreach ($this->eventListenersByName[$eventName] as $listener) {
call_user_func_array($listener, $eventArgs);
}
}
}
class Auction implements Observable {
private $eventEmitter;
public function __construct() {
$this->eventEmitter = new EventEmitter();
}
function addBid($bidderName, $bidAmount) {
$this->eventEmitter->triggerEvent('bid', [$bidderName, $bidAmount]);
}
function addEventListener($eventName, callable $listener) {
$this->eventEmitter->addEventListener($eventName, $listener);
}
function removeEventListener($eventName, callable $listener) {
$this->eventEmitter->removeEventListener($eventName, $listener);
}
function removeAllEventListeners($eventName) {
$this->eventEmitter->removeAllEventListeners($eventName);
}
}
Here's how #3 (traits) would look like:
trait EventEmitterTrait {
private $eventListenersByName = [];
function addEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName][] = $listener;
}
function removeEventListener($eventName, callable $listener) {
$this->eventListenersByName[$eventName] = array_filter($this->eventListenersByName[$eventName], function($existingListener) use ($listener) {
return $existingListener === $listener;
});
}
function removeAllEventListeners($eventName) {
$this->eventListenersByName[$eventName] = [];
}
protected function triggerEvent($eventName, array $eventArgs) {
foreach ($this->eventListenersByName[$eventName] as $listener) {
call_user_func_array($listener, $eventArgs);
}
}
}
class Auction implements Observable {
use EventEmitterTrait;
function addBid($bidderName, $bidAmount) {
$this->triggerEvent('bid', [$bidderName, $bidAmount]);
}
}
Note that the code inside the EventEmitterTrait is exactly the same as what's inside the EventEmitter class except the trait declares the triggerEvent() method as protected. So, the only difference you need to look at is the implementation of the Auction class.
And the difference is large. When using composition, we get a great solution, allowing us to reuse our EventEmitter by as many classes as we like. But, the main drawback is the we have a lot of boilerplate code that we need to write and maintain because for each method defined in the Observable interface, we need to implement it and write boring boilerplate code that just forwards the arguments onto the corresponding method in our composed the EventEmitter object. Using the trait in this example lets us avoid that, helping us reduce boilerplate code and improve maintainability.
However, there may be times where you don't want your Auction class to implement the full Observable interface - maybe you only want to expose 1 or 2 methods, or maybe even none at all so that you can define your own method signatures. In such a case, you might still prefer the composition method.
But, the trait is very compelling in most scenarios, especially if the interface has lots of methods, which causes you to write lots of boilerplate.
* You could actually kinda do both - define the EventEmitter class in case you ever want to use it compositionally, and define the EventEmitterTrait trait too, using the EventEmitter class implementation inside the trait :)

The main difference is that, with interfaces, you must define the actual implementation of each method within each class that implements said interface, so you can have many classes implement the same interface but with different behavior, while traits are just chunks of code injected in a class; another important difference is that trait methods can only be class-methods or static-methods, unlike interface methods which can also (and usually are) be instance methods.

The trait is same as a class we can use for multiple inheritance purposes and also code reusability.
We can use trait inside the class and also we can use multiple traits in the same class with 'use keyword'.
The interface is using for code reusability same as a trait
the interface is extend multiple interfaces so we can solve the multiple inheritance problems but when we implement the interface then we should create all the methods inside the class.
For more info click below link:
http://php.net/manual/en/language.oop5.traits.php
http://php.net/manual/en/language.oop5.interfaces.php

An interface is a contract that says “this object is able to do this thing”, whereas a trait is giving the object the ability to do the thing.
A trait is essentially a way to “copy and paste” code between classes.
Try reading this article, What are PHP traits?

Related

unit tests and object-inheritance

I have a question concerning "unit tests" and object-inheritance. For example:
I have a class A which extends class B. Let's assume the only difference of the two classes is the add method . In class B this add method is slightly extended. Now I want to write a unit test for the add function of class B but because of the parent::add call I have a dependency to the parent class A. In this case I can't mock the add method of the parent class so the resulting test will be a integration test but if I want it to be a unit test? I don't want the the test for method add in class B fails because of the parent method in class A. In this case only the unit-test of the parent method should fail.
class B exends A
{
public function add($item)
{
parent::add($item);
//do some additional stuff
}
....
}
class A
{
protected $items = [];
public function add($item)
{
$this->items[] = $item;
}
....
}
Surely I could use object-aggregation and pass my parent object to the child contructor and therefore I would be able to mock the parent method add, but is this the best approach? I would rarely use object-inheritance anymore.
class B
{
protected $a;
public function __contruct(A $a)
{
$this->a = $a;
}
public function add($item)
{
$this->a->add($item);
//do some additional stuff
}
....
}
class A
{
protected $items = [];
public function add($item)
{
$this->items[] = $item;
}
....
}
I would be very grateful for your opinions. Thanks!
Ask yourself, what kind of inheritance do you want to achieve? If B is a kind of A, then you're wanting interface inheritance. If B shares a lot of code with A, then you're wanting implementation inheritance. Sometimes you want both.
Interface inheritance classifies semantic meaning into a strict hierarchy, with that meaning organized from generalized to specialized. Think taxonomy. The interface (method signatures) represent the behaviors: both the set of messages to which the class responds, as well as the set of messages that the class sends. When inheriting from a class, you implicitly accept responsibility for all messages the superclass sends on your behalf, not just the messages that it can receive. For this reason, the coupling between super- and sub-class is tight and each must strictly substitute for the other (see Liskov Substitution Principle).
Implementation inheritance encapsulates the mechanics of data representation and behavior (properties and methods) into a convenient package for reuse and enhancement by sub-classes. By definition, a sub-class inherits the interface of the parent even if it only wants the implementation.
That last part is crucial. Read it again: Sub-classes inherit the interface even if they only want the implementation.
Does B strictly require the interface of A? Can B substitute for A, in all cases matching co-variance and contra-varience?
If the answer is yes, then you have true sub-typing. Congratulations. Now you must test the same behaviors twice, because in B you are responsible for maintaining the behaviors of A: for every thing A can do, B must be able to do.
If the answer is no, then you merely need to share the implementation, test that the implementation works, then test that B and A separately dispatch into the implementation.
In practical terms, I avoid extends. When I want implementation inheritance, I use trait to define static behaviors † in one place, then use to incorporate it where needed. When I want interface inheritance, I define many narrow interface then combine with implements in all the concrete types, possibly using trait to leverage behavior.
For your example, I'd do this:
trait Container {
public function add($item) { $this->items[] = $item; }
public function getItems() { return $this->items; }
private $items = [];
}
interface Containable { public function add($item); }
class A implements Containable { use Container; }
class B implements Containable {
use Container { Container::add as c_add; }
public function add($item) {
$this->c_add($item);
$this->mutate($item);
}
public function mutate($item) { /* custom stuff */ }
}
Container::add and B::mutate would have unit tests, while B::add would have an integration test.
In summary, favor composition over inheritance because extends is evil. Read the ThoughtWorks primer Composition vs. Inheritance: How To Choose to gain a deeper understanding of the design trade-offs.
† "static behaviors", you ask? Yes. Low-coupling is a goal and this goes for traits. As much as possible, a trait should reference only variables it defines. The safest way to enforce that is with static methods that take all their input as formal arguments. The easiest way is to define member variables in the trait. (But, please, avoid having traits use member variables that are not clearly defined in the trait -- otherwise, that's blind coupling!) The problem, I find, with trait member variables is that when mixing in multiple traits you increase the chance of collision. This is, admittedly, small, but it is a practical consider for library authors.

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());

Two different ways to implement Decorator pattern in PHP

While doing some tutorials on Decorator pattern, I've encountered two different implementations.
Implementation 1 (referred to as I1)
Implementation 2 (referred to as I2)
In short,
I1's parent decorator class implements original object's interface (In the example, class PropertyDecorator implements PropertyInterface. The original object Property implements PropertyInterface as well).
I2's parent decorator class DOES NOT implement original object's interface (In the example, Decorator_Wrapper does not implements Cupcake interface. In fact, there is not even CupcakeInterface at all).
My question is,
Is this merely a personal preference of understanding and implementing Decorator pattern? or one is wrong and one is right?
Just depends on your needs.
Let's see:
Abstract class
Can provide abstract methods.
Can provide real functions and variables.
Can be extended. But a class can extend only 1 parent.
Interface
Can provide abstract methods.
A class may implement several interfaces.
I generally would prefer using a base abstract class, because I can declare some basic functions as well, since you could have a lot of different types of decorators with similar functionality. Methods can be overriden anyways + you can implement some interfaces.
class Decorator extends Decorator_Wrapper implements Interface1, Inteface2 {
public function __construct(){
parent::__construct() ; // Here you could perform some basic decorator actions. It is an advantage compared to interfaces.
}
}
The Decorator pattern is used when you wish to extend the functionality of an instance of a class without extending the class itself (thus, not affecting other instances of said class).
It's kind of an extension at runtime and it's pretty useful since it lets you customize the behavior of an object at runtime. You can even "simulate" multiple inheritance with it.
Since both your examples accomplish this, both are correct. There is no need for a decorator to implement the base interface or extend the original object.
HOWEVER...
If the decorator does not implement the base interface, it MIGHT not be able to be used interchangeably with the original class.
Which might defeat the purpose of using the decorator if you can't use it everywhere "safely".
Example:
interface FooInterface {
public function scare();
}
class Foo implements FooInterface {
protected $boo = 'boo';
public function scare() { echo $this->boo; }
}
class FooBar {
public function __construct(FooInterface $foo) {
$this->foo = $foo;
}
public function scareAlot() {
echo strtoupper($this->foo->scare());
}
}
class INeedFoo {
public static function gimmeFoo(FooInterface $foo) {}
}
$foo = new Foo();
$fooBar = new FooBar($foo);
INeedFoo::gimmeFoo($foo); //Works
INeedFoo::gimmeFoo($fooBar); //Does not Work
Also, if you implement the base interface or extend the base class it might be easier to add multiple decorators on top of eachother but ... you may also end up with a lot of replicated functionality.

PHP - Traits as helpers

Are there any contradictions to use traits to inject helper methods like this?
class Foo
{
use Helper\Array;
function isFooValid(array $foo)
{
return $this->arrayContainsOnly('BarClass', $foo);
}
}
That's the idea with traits.
However you should still keep an eye out for coupled code. If Helper\Array is a completely different namespace from what Foo is in you might want to re-think this particular approach.
Traits have been added to PHP for a very simple reason: PHP does not support multiple inheritance. Simply put, a class cannot extends more than on class at a time. This becomes laborious when you need functionality declared in two different classes that are used by other classes as well, and the result is that you would have to repeat code in order to get the job done without tangling yourself up in a mist of cobwebs.
Enter traits. These allow us to declare a type of class that contains methods that can be reused. Better still, their methods can be directly injected into any class you use, and you can use multiple traits in the same class. Let's look at a simple Hello World example.
<?php
trait SayHello
{
private function hello()
{
return "Hello ";
}
private function world()
{
return "World";
}
}
trait Talk
{
private function speak()
{
echo $this->hello() . $this->world();
}
}
class HelloWorld
{
use SayHello;
use Talk;
public function __construct()
{
$this->speak();
}
}
$message = new HelloWorld(); // returns "Hello World";
In my opinion and talking about cohesion within an application, distributing responsibilties is a good thing but scattering responsibilties is really something else that have nothing to do with design by contract.
This is my concern with traits as helpers.
I've been thinking a lot about traits place in an architecture and I really think traits should be taken for what they are : shared implementation meaning shared encapsulation.
So they should not replace interfaces but stay behind them.
I take "interface" in the architectural and language-agnostic sense not idiosyncratic sense given the fact that PHP-specific interfaces are just an abstraction tool whereas traits are nothing but an implementation tool.
Interfaces come before implementations.Rely on abstract/interfaces and not on concrete/details.
So it's important to keep in mind that traits don't structure application architectures no more they initiate class contracts but stand behind them and at the service of them.

What is the difference between abstract and interface in php? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
PHP: What is the difference between an interface and abstract class?
As far as I understand, a class implements or extends abstract or interface class has to use the default methods. I know we can use implement keyword to use multiple interfaces, but we only can extend 1 abstract. Which one to use in real life project and the difference?
The differences are both theoretical and practical:
interface is a description of some capability your class has and advertises (so various classes implementing the same interface can be used the same way)
abstract class can be a default implementation, containing the parts which are likely to appear in all the implementations. It doesn't have to implement the complete interface
Example - an interface:
// define what any class implementing this must be capable of
interface IRetrieveData {
// retrieve the resource
function fetch($url);
// get the result of the retrieval (true on success, false otherwise)
function getOperationResult();
// what is this class called?
function getMyClassName();
}
Now we have the set of requirements that will be checked for every class implementing this. Let's make an abstract class and its children:
// define default behavior for the children of this class
abstract class AbstractRetriever implements IRetrieveData {
protected $result = false;
// define here, so we don't need to define this in every implementation
function getResult() {
return $result;
}
// note we're not implementing the other two methods,
// as this will be very different for each class.
}
class CurlRetriever extends AbstractRetriever {
function fetch($url) {
// (setup, config etc...)
$out = curl_execute();
$this->result = !(curl_error());
return $out;
}
function getMyClassName() {
return 'CurlRetriever is my name!';
}
}
class PhpRetriever extends AbstractRetriever {
function fetch($url) {
$out = file_get_contents($url);
$this->result = ($out !== FALSE);
return $out;
}
function getMyClassName() {
return 'PhpRetriever';
}
}
A completely different abstract class (unrelated to the interface), with a subclass which implements our interface:
abstract class AbstractDog {
function bark() {
return 'Woof!';
}
}
class GoldenRetriever extends AbstractDog implements IRetrieveData {
// this class has a completely different implementation
// than AbstractRetriever
// so it doesn't make sense to extend AbstractRetriever
// however, we need to implement all the methods of the interface
private $hasFetched = false;
function getResult() {
return $this->hasFetched;
}
function fetch($url) {
// (some retrieval code etc...)
$this->hasFetched = true;
return $response;
}
function getMyClassName() {
return parent::bark();
}
}
Now, in other code, we can do this:
function getStuff(IRetrieveData $retriever, $url) {
$stuff = $retriever->fetch($url);
}
and we don't have to worry which of the retrievers (cURL, PHP, or Golden) will be passed in, and how are they going to accomplish the goal, as all should be capable of behaving similarly. You could do this with an abstract class, too, but then you're restricting yourself based on the classes' ancestor, instead of its capability.
Multiple vs. single inheritance:
You can only inherit from a single abstract class
You can implement multiple interfaces
Implementation:
An abstract class can actually have functioning code in it. This lets you share implementation between the child classes
An interface only defines public member functions. Classes implementing the same interface don't actually share code.
That's what I know off the top of my head.
The metaphor I heard best was that an abstract class is a half-completed class. It's not done; you still have to finish it. So when you make a class that extends an abstract class, you are just completing what you began in the abstract class. This is also why you can't instantiate an abstract class; that you've made it abstract indicates that it's incomplete. It still needs some additional functionality.
An an interface just guarantees that certain methods, each with a certain number of arguments, must exist within a class that implements it. So that later on, a programmer who uses a class that implements a particular interface can rest assured that they can call certain methods on that class.
See this page: 5 Main Difference between Abstract class and Interface in PHP
And this: related StackOverflow answer.
Here's a good description of the differences between the two:
http://www.supertom.com/code/php_abstracts_and_interfaces.html
It all boils down to the fact that extends is a "is-a" relationship while implements is a "has-a" relationship.
"An Abstract Class can contain default Implementation, where as an
Interface should not contain any implementation at all. "
As far as which to use in real world application... it really comes down to context.
For example, there was a question on here the other day about implementing a game using PHP. Here they had a abstract class defining a monster and any monster could be based off of this abstract class. This allowed for inheritance of default monster properties.
Whereas for an interface, you are defining a general requirements for a way to "interface" (pardon using the term in the explanation) some system. An example of this from a recent project I did. I implemented a soapclient in php to interact with a soapserver from a third party. This interface defines what soap methods the server supports and thus any class implementing my interface must define those methods.

Categories