Skip to content

Instantly share code, notes, and snippets.

@rmruano
Last active December 15, 2015 04:09
Show Gist options
  • Select an option

  • Save rmruano/5199690 to your computer and use it in GitHub Desktop.

Select an option

Save rmruano/5199690 to your computer and use it in GitHub Desktop.
Iterable group of typed objects, can be easily refactored to only allow scalars.
<?php
namespace Model\User\UserItem;
/**
* Iterable group of UserItems
*/
class Group implements \Iterator {
private $position = 0;
private $objects = array();
private $size = 0;
public function __construct() {
$this->rewind();
}
/* ▼ CUSTOM METHODS ....................................................... */
/**
* Adds an item to the group
* @param \Model\User\UserItem $userItem
*/
public function add(\Model\User\UserItem $userItem) {
$this->objects[]=$userItem;
$this->size++;
}
/**
* Returns the user item at the position specified
* @param int $idx index number to retrieve, null to get the current one
* @throws \Exception
* @return \Model\User\UserItem:
*/
public function get($idx=null) {
if ($idx === null) return current();
if(!$this->valid($idx)) throw new \Exception("Index not found");
return $this->objects[$idx];
}
/**
* Returns the group size
* @return int
*/
function size() {
return $this->size;
}
/**
* Is the group empty?
* @return boolean
*/
function isEmpty() {
if ($this->size()===0) return true;
return false;
}
/* ▼ INTERFACE IMPLEMENTATION ....................................................... */
/**
* @see Iterator::current()
* @return \Model\User\UserItem
*/
function current() {
return $this->objects[$this->position];
}
function rewind() {
$this->position = 0;
}
function key() {
return $this->position;
}
function next() {
++$this->position;
}
function valid() {
return isset($this->objects[$this->position]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment