Skip to content

Instantly share code, notes, and snippets.

@perrupa
Forked from eric1234/null_pattern.php
Last active May 28, 2018 17:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perrupa/9508b7b5aa0ba66cdc32 to your computer and use it in GitHub Desktop.
Save perrupa/9508b7b5aa0ba66cdc32 to your computer and use it in GitHub Desktop.
<?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