Interfaces in PHP 7


Interfaces are also called contracts. It actually defines the syntactical contract that all the derived classes should follow. Let us consider an example first to understand how this contract works.

interface InputOrderDetails {
public function UpdateCustomerStatus();
public function TakeOrder();
}
class ItemDetails implements InputOrderDetails {
public function UpdateCustomerStatus(){
var_dump("Updating customer...");
}
public function TakeOrder(){
var_dump("Taking orders..");
}
}
$item1 = new ItemDetails;
$item1->TakeOrder();
$item1->UpdateCustomerStatus();

We have an interface which defines a syntactical contract and the class follows those contracts exactly as it has been defined.
Look at the output.


string(15) "Taking orders.."
string(20) "Updating customer..."

Now we can move forward this contract to furthermore. We can imagine a situation where we can use our interface concept to hide information. Consider the contract between the seller companies a buyer. The buyer does not know how the product reaches to her. Besides, the seller also does not want to accept the responsibility of carrying the product on its own to the house of the buyer. So the company gives that responsibility to a courier company. Now the courier receives the product from the seller and carries to the buyer.
In this scenario, the courier does not know what type of product it’s carrying to the buyer. We follow the SOLID Design principle exactly as we have wished to do.
Let us see the code, it tells a relationship and messaging between many objects.

deliverer = $deliverer;        
    }
    public function recieve() {
        $user = "Sanjib";
        $this->deliverer->deliver($user);        
    }
}

$user = new User(new Retailer());
$user->recieve();

The ‘Retailer’ delivers the instruction to the ‘Deliverer’. So there is a contract between them and the retailer needs user as a parameter to whom it will send the item. Retailer knows the nature of the item, what item it’s sending; but deliverer doesn’t know about it. The deliverer only delivers and does not know anything. The buyer only receives, so she needs one ‘deliverer object’ who will deliver. Exactly the same thing happens here. Look at the code and the output below.

string(25) "One book sent to...Sanjib"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s