PHP Interfaces Quickstart

PHP interfaces are still quite new to most. Below is a simple demonstration of their usefulness. I think I’d seen this within one of the many fantastic laravel books.

~

PHP interfaces are still quite new to most. Below is a simple demonstration of their usefulness. I think I’d seen this within one of the many fantastic laravel books.

<?php  
interface BillerInterface {  
    public function bill(array $user, $amount);
}
interface BillingNotifierInterface {  
    public function notify(array $user, $amount);
}


class NotifyByEmail implements BillingNotifierInterface {  
    public function notify(array $user, $amount)
    {
        echo "Send email for ".$user["name"]." of $amount".PHP_EOL;
    }
}


class NotifyByMessage implements BillingNotifierInterface {  
    public function notify(array $user, $amount)
    {
        echo "Display message for ".$user["name"]." of $amount".PHP_EOL;
    }
}


class NotifyBySMS implements BillingNotifierInterface {  
    public function notify(array $user, $amount)
    {
        echo "Send SMS for ".$user["name"]." of $amount".PHP_EOL;
    }
}


class StripeBiller implements BillerInterface {  
    public function __construct(BillingNotifierInterface $notifier)
    {
        $this->notifier = $notifier;
    }

    public function bill(array $user, $amount)
    {
        // Bill the user via Stripe...
        echo "Bill via Stripe".PHP_EOL;
        $this->notifier->notify($user, $amount);
    }
}


class PaypalBiller implements BillerInterface {  
    public function __construct(BillingNotifierInterface $notifier)
    {
        $this->notifier = $notifier;
    }

    public function bill(array $user, $amount)
    {
        echo "Bill via Paypal".PHP_EOL;
        $this->notifier->notify($user, $amount);
    }
}


class EPDQBiller implements BillerInterface {  
    public function __construct(BillingNotifierInterface $notifier)
    {
        $this->notifier = $notifier;
    }


    public function bill(array $user, $amount)
    {
        echo "Bill via ePDQ".PHP_EOL;
        $this->notifier->notify($user, $amount);
    }
}


$newBill = new StripeBiller(new NotifyBySMS);
$newBill->bill(
    array(
        "name" => "Scott Wilcox"
    ),
    "123.89"
);
$newBill = new PaypalBiller(new NotifyByMessage);
$newBill->bill(
    array(
        "name" => "Scott Wilcox"
    ),
    "123.89"
);
$newBill = new EPDQBiller(new NotifyByEmail);
$newBill->bill(
    array(
        "name" => "Scott Wilcox"
    ),
    "123.89"
);

 


~

Comments