Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created December 11, 2019 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/2cd727220855b408792c56bd3dcac92c to your computer and use it in GitHub Desktop.
Save kobus1998/2cd727220855b408792c56bd3dcac92c to your computer and use it in GitHub Desktop.
abstraction shopping cart checkout
<?php
class Product
{
protected $id;
protected $name;
public function __construct($id, $name)
{
$this->id = $id;
$this->name = $name;
}
}
class User
{
protected $id;
protected $shoppingCart;
public function __construct($id, $shoppingCart)
{
$this->id = $id;
$this->shoppingCart = $shoppingCart;
}
}
class ShoppingCart
{
protected $id;
protected $products = [];
public function __construct($id, $products)
{
$this->id = $id;
$this->prododucts = $products;
}
public function checkout($payment)
{
if (empty($this->products)) {
throw new \Exception('empty prodcucts');
}
if (!$payment->valid()) {
throw new \Exception('Card not valid');
}
return $payment;
}
}
class PaymentMethod
{
protected $card;
public function __construct($card)
{
$this->card = $card;
}
public function valid()
{
return !empty($this->card['number']);
}
}
$u = new User(1, new ShoppingCart(1, [
new Product(1, 'a'),
new Product(2, 'b'),
new Product(3, 'c'),
]));
$u->shoppingCart->checkout(new PaymentMethod([
'number' => '123...',
'cvv' => '123',
'dateExp' => '01-2021',
'name' => 'john doe'
]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment