-
-
Save perrupa/9508b7b5aa0ba66cdc32 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Implements a recursive null object pattern. | |
# | |
# Implemented as a trait so any object can make it's properties use | |
# the null pattern without resorting to inheritance. | |
# | |
# The goal is so you can pull data off a partially populated object | |
# without excessive existance checks. | |
trait NullPattern { | |
# The real data we are wrapping. Since we continually return wrapped | |
# objects if you ever want a unwrapped object the property can be | |
# simply accessed | |
public $__value__; | |
function __call($name, $arguments) { | |
$value = null; | |
if( is_object($this->__value__) && method_exists($this->__value__, $name) ) { | |
$value = call_user_func_array(array($this->__value__, $name), $arguments); | |
} | |
return new NullObject( $value ); | |
} | |
function __get($name) { | |
$value = null; | |
if( is_object($this->__value__) && property_exists($this->__value__, $name) ) { | |
$value = $this->__value__->$name; | |
} | |
return new NullObject( $value ); | |
} | |
function __set($name, $value) { | |
if( is_object($this->__value__) ) | |
$this->__value__->$name = $value; | |
} | |
function __toString() { | |
if( is_array($this->__value__) ) | |
return implode(', ', $this->__value__); | |
else | |
return (string) $this->__value__; | |
} | |
} | |
# A general object that uses the NullPattern trait. Make it easy to | |
# turn any piece of data into something that behaves with the | |
# NullPattern. | |
class NullObject { | |
use NullPattern; | |
# Constructor to wrap a value in a NullObject object | |
function __construct( $value = null ) { | |
$this->__value__ = $value; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment