09. December 2013

An implementation of the memento pattern in PHP

The memento pattern is a design pattern used to store and revert states for objects which support this capacity. It is accomplished by having a Caretaker object which manages a set of states, encoded in Memento objects. The Memento objects handle the storage of state; the implementation of this can vary, but it necessitates some level of deep-copying the object. A shallow copy will not suffice in general because it will not always capture the whole state of an object, due to the fact that most languages implement memory access for objects as references. Because of this, I use serialize and unserialize in my example below. Of course you could use other methods, like clone or just copying what you know you will need if memory is a concern.

more

04. December 2013

Weighted merging of multiple Markov Chains

Suppose you have ten text sources, and you generate a new block of text trained from each, and you want to give each its own weighting. You have to weave multiple markov chains together.

more

18. November 2013

Registry Pattern

Here’s another super-simple design pattern, implemented in PHP.

class Registry {
    private $values = array();

    public function get($key) {
        if (!isset($this->values->$key)) {
            throw new OutOfBoundsException("$key not in registry");
        }
        return $this->values->$key;
    }

    public function set($key, $val) {
        if (!isset($this->values->$key)) {
            throw new OverflowException("$key already in registry");
        }
        $this->values->$key = $val;
    }
}

The registry pattern is used to store information that can be used throughout your application. You could use a registry to store a bunch of application settings, for example.

I’ve seen this implemented with the magic getters and setters in php, but then you end up with an object that appears to just be setting public properties. It’s not the most readable solution and it is unintuitive to expect an exception when setting a public property.

It is often implemented as a singleton, but it doesn’t have to be. In general singletons are bad because they introduce global state into your code and are hard to write test cases for. If you don’t want to use your registry as a singleton, just do an inversion of control. The downside is having to pass around the registry as a parameter, but trust me: it’s worth the effort.