Skip to content

Instantly share code, notes, and snippets.

@MontealegreLuis
Created July 24, 2014 03:44
Show Gist options
  • Save MontealegreLuis/bf9dcb4f888f310bbe36 to your computer and use it in GitHub Desktop.
Save MontealegreLuis/bf9dcb4f888f310bbe36 to your computer and use it in GitHub Desktop.
Abstract class, interface, and trait example.
<?php
class Autoloader
{
/**
* @param string $className
*/
public function autoload($className)
{
require str_replace('\\', '/', $className) . '.php';
}
public function register()
{
spl_autoload_register([$this, 'autoload']);
}
}
<?php
namespace Company;
use JsonSerializable;
class DownloadableProduct extends Product implements JsonSerializable
{
use ProvidesJsonEncoding;
/** @type string */
protected $file;
/**
* @param string $name
* @param Money $price
* @param string $file
*/
public function __construct($name, Money $price, $file)
{
parent::__construct($name, $price);
$this->file = $file;
}
}
<?php
namespace Company;
use JsonSerializable;
class Money implements JsonSerializable
{
use ProvidesJsonEncoding;
/** @type integer */
protected $amount;
/** @type string */
protected $currency;
/**
* @param integer $amount
* @param string $currency
*/
public function __construct($amount, $currency)
{
$this->amount = $amount;
$this->currency = $currency;
}
}
<?php
namespace Company;
abstract class Product
{
/** @type string */
protected $name;
/** @type Money */
protected $price;
/**
* @param string $name
* @param Money $price
*/
public function __construct($name, Money $price)
{
$this->name = $name;
$this->price = $price;
}
}
<?php
namespace Company;
trait ProvidesJsonEncoding
{
/**
* @return array
*/
public function jsonSerialize()
{
$json = get_object_vars($this);
foreach ($json as $key => $property) {
if ($property instanceof CastsToJson) {
$json[$key] = $property->jsonSerialize();
}
}
return $json;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment