Skip to content

Instantly share code, notes, and snippets.

@VassilisPallas
Last active February 28, 2017 12:38
Show Gist options
  • Save VassilisPallas/bf91f0d5eab73b0ac23955101dcae98a to your computer and use it in GitHub Desktop.
Save VassilisPallas/bf91f0d5eab73b0ac23955101dcae98a to your computer and use it in GitHub Desktop.
Custom Collection class for php
<?php
namespace App;
/**
* Created by PhpStorm.
* User: Vassilis Pallas
* Date: 7/6/16
* Time: 1:44 AM
*/
class Collection
{
private $items = array();
public function addItem($key = null, $obj)
{
if ($key == null) {
$this->items[] = $obj;
} else {
if (isset($this->items[$key])) {
// throw new KeyHasUseException("Key $key already in use.");
throw new Exception("Key $key already in use.");
} else {
$this->items[$key] = $obj;
}
}
}
public function deleteItem($key)
{
if (isset($this->items[$key])) {
unset($this->items[$key]);
} else {
// throw new KeyInvalidException("Invalid key $key.");
throw new Exception("Invalid key $key.");
}
}
public function getItem($key)
{
if (isset($this->items[$key])) {
return $this->items[$key];
} else {
// throw new KeyInvalidException("Invalid key $key.");
throw new Exception("Invalid key $key.");
}
}
public function size()
{
return count($this->items);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment