Skip to content

Instantly share code, notes, and snippets.

@sbisbee
Created March 19, 2011 22:18
Show Gist options
  • Save sbisbee/877860 to your computer and use it in GitHub Desktop.
Save sbisbee/877860 to your computer and use it in GitHub Desktop.
The boiler plate Value Object that I've been using on projects for a few years now.
<?php
abstract class ValueObject
{
public function __construct($src = null)
{
if($src)
self::populate($src);
}
/**
* @var mixed An associative array or object that will be mapped into the VO.
* @return void
*/
public function populate($src)
{
if(!is_object($src) && !is_array($src))
throw new Exception('You can only populate VOs with objects and arrays.');
foreach($src as $k => $v)
if(property_exists($this, $k))
$this->$k = $v;
// These next two items are useful for when you're using CouchDB.
if(!empty($src->_id))
$this->_id = $src->_id;
if(!empty($src->_rev))
$this->_rev = $src->_rev;
}
/**
* @var ValueObject Another VO of the same type to compare to.
* @return bool
*/
public function equals($alt)
{
if(!isset($alt) || !($this instanceof $alt))
return false;
foreach($alt as $k => $v)
if($this->$k !== $v)
return false;
return true;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment