Skip to content

Instantly share code, notes, and snippets.

@chrisamoore
Created January 28, 2013 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chrisamoore/4658308 to your computer and use it in GitHub Desktop.
Save chrisamoore/4658308 to your computer and use it in GitHub Desktop.
Mediator use in separate class
<?php
$start = microtime();
require_once '../config/config.php';
require_once CORE . 'lib/Order/Order.php';
$class = basename(__FILE__);
$test = $_GET['test'];
$order = new Order(2);
switch ($test) {
case 'test':
$data = 'test';
break;
case 'getOrderStatus':
$data = $order->changeOrderStatus('Unassigned');
break;
default:
$data = 'GET condition not met';
break;
}
include 'req/data.php';
<?php
class Order
{
public $id;
function __construct($id)
{
$this->mediator = new Mediator();
}
public function changeOrderStatus($status)
{
$value = $this->getOrderStatusValue($status);
$sql['changeOrderStatus'] = 'UPDATE `orders`
SET `order_status` = ?
WHERE `id` = ' . $this->id;
$sth = $this->dbh->prepare($sql['changeOrderStatus']);
$sth->execute(array($value));
$this->mediator->trigger($status, $this->id);
return;
}
<?php
/**
* @usage
* $mediator = new Mediator;
* $mediator->attach('load', function() { echo "Loading"; });
* $mediator->attach('stop', function() { echo "Stopping"; });
* $mediator->attach('stop', function() { echo "Stopped"; });
* $mediator->trigger('load'); // prints "Loading"
* $mediator->trigger('stop'); // prints "StoppingStopped"
*/
class Mediator {
protected $events = array();
public function attach($eventName, $callback) {
if (!isset($this->events[$eventName])) {
$this->events[$eventName] = array();
}
$this->events[$eventName][] = $callback;
}
public function trigger($eventName, $data = null) {
foreach ($this->events[$eventName] as $callback) {
$callback($eventName, $data);
}
$this->log($eventName, $data);
}
public function log($value, $params = null){
trigger_error("Mediator->trigger Event: " . $value . json_encode($params));
}
}
<?php
require_once CORE . 'lib/Mediator/Mediator.php';
/**
* @occurances found at SVN Rev #2841
*/
// Event listener
$mediator = new Mediator;
// Methods to be triggered
$mediator->attach('demo', function(){
$foo = new Demo();
$foo->bar('baz');
});
$mediator->attach('Unassigned', function(){
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment