Skip to content

Instantly share code, notes, and snippets.

@carousel
Created March 26, 2018 18:40
Show Gist options
  • Save carousel/f80f1f2989e22d5a1557acef55363519 to your computer and use it in GitHub Desktop.
Save carousel/f80f1f2989e22d5a1557acef55363519 to your computer and use it in GitHub Desktop.
Typed collection in php (collection of objects) for usage in DDD projects.
<?php
interface Vehicle{}
class Car implements Vehicle{}
class Track implements Vehicle{}
class Fruit{}
class Collection
{
protected $items = [];
protected $type;
public function __construct($type)
{
$this->type = $type;
}
public function add($item)
{
if ($item instanceof $this->type) {
if (!in_array($item, $this->items)) {
$this->items[] = $item;
}
} else {
throw new Exception(get_class($item) . ' must be instance of Vehicle');
}
}
public function getItems()
{
if (count($this->items) != 0) {
return $this->items;
} else {
throw new Exception('There is no items in collection');
}
}
public function flush()
{
$this->items = [];
}
public function remove($item)
{
if (count($this->items) > 0) {
foreach ($this->items as $key => $val) {
if (get_class($item) == get_class($val)) {
unset($this->items[$key]);
}
}
} else {
throw new Exception('There is no items in collection');
}
}
public function count()
{
return count($this->items);
}
}
class VehicleCollection extends Collection
{
}
$vc = new VehicleCollection('Vehicle');
$car = new Car;
$track = new Track;
$fruit = new Fruit;
//$vc->add($fruit);
$vc->add($track);
$vc->add($car);
$vc->remove($track);
//$vc->flush();
echo $vc->count() . " items in collection \n";
$items = $vc->getItems();
foreach ($items as $key => $val) {
echo $key . " => " . get_class($val) . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment