Chains

Last updated: August 12th, 2023
Release:

An execution system inspired by the chain-of-responsibility design pattern.

Concept

Similar to the chain-of-responsibility pattern, chains are groups of one (1) or more processing objects - called nodes - which receive data as it passes along the group, or chain.

The entire system revolves around the ChainHelper class. It facilitates the linking of processing nodes together and sending data along the 'chain' of nodes to be processed in order. Nodes must all derive from the NodeBase abstract class, and the data sent traversing a chain must derive from the DispatchBase abstract class.

Quick Example

Before going any further, let's see a (very simplistic) chain in action:

<?php

	use Stoic\Chain\DispatchBase;
	use Stoic\Chain\NodeBase;
	use Stoic\Chain\ChainHelper;

	class IncrementDispatch extends DispatchBase {
		public function initialize($input) {
			$this->makeValid();

			return;
		}

		public function increment($number) {
			return ++$number;
		}
	}

	class IncrementNode extends NodeBase {
		public function __construct() {
			$this->setKey('incrementNode');
			$this->setVersion('1.0.0');

			return;
		}

		public function process($sender, DispatchBase &$dispatch) {
			if (!($dispatch instanceof IncrementDispatch)) {
				return;
			}

			$dispatch->setResult($dispatch->increment(1));

			return;
		}
	}

	$chain = new ChainHelper();
	$chain->linkNode(new IncrementNode());

	$dispatch = new IncrementDispatch();
	$dispatch->initialize(null);

	$success = $chain->traverse($dispatch);
	$results = $dispatch->getResults();

	print_r($results);

The above example creates two classes:

  1. IncrementDispatch - A dispatch class that can increment a number
  2. IncrementNode - A node class that asks the dispatch to increment and store a number

This example isn't very useful, but it does exercise all parts of the Chain system. For more details on the system, read on!

Further Reading

Next Up

Continue to read about dispatches, or visit the Table of Contents.