Skip to content

Instantly share code, notes, and snippets.

@iamdtang
Created January 23, 2018 06:59
Show Gist options
  • Save iamdtang/8105f06a5e8d40b006c77f0cdac3f11b to your computer and use it in GitHub Desktop.
Save iamdtang/8105f06a5e8d40b006c77f0cdac3f11b to your computer and use it in GitHub Desktop.
<?php
class ShoppingCart {
protected $lineItems = [];
public function add($lineItem)
{
$this->lineItems[] = $lineItem;
}
public function getTotal()
{
$total = 0;
foreach($this->lineItems as $lineItem) {
$total += $lineItem->getTotal();
}
return $total;
}
}
class LineItem {
public $product, $quantity;
public function __construct(Product $product, int $quantity)
{
$this->product = $product;
$this->quantity = $quantity;
}
public function getTotal()
{
return $this->quantity * $this->product->price;
}
}
class Product {
public $name, $price;
public function __construct($name, $price)
{
$this->name = $name;
$this->price = $price;
}
}
$album = new Product('Bright Soundtrack', 10.99);
$song = new Product('The Break Up by MGK', 0.99);
$show = new Product('Big Bang Theory Season 1', 34.99);
$cart = new ShoppingCart();
$cart->add(new LineItem($album, 1));
$cart->add(new LineItem($song, 1));
$cart->add(new LineItem($show, 1));
echo $cart->getTotal();
echo '<br>';
// Example 2
class Track extends Product {
protected $bytes;
public static function find($id, $pdo)
{
$statement = $pdo->prepare('
select *
from tracks
where TrackId = ?
');
$statement->bindParam(1, $id);
$statement->execute();
$track = $statement->fetch(PDO::FETCH_OBJ);
return new Track($track);
}
public function __construct($track)
{
$this->name = $track->Name;
$this->price = $track->UnitPrice;
$this->bytes = $track->Bytes;
}
public function getSize($size)
{
switch ($size) {
case 'B':
return $this->bytes;
case 'KB':
return $this->bytes * pow(10, -3);
case 'MB':
return $this->bytes * pow(10, -6);
}
}
}
$pdo = new PDO('sqlite:chinook.db');
$track = Track::find(2166, $pdo);
echo $track->getSize('MB');
echo '<br>';
$cart->add(new LineItem($track, 1));
echo $cart->getTotal();
echo '<br>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment