Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 83 lines (62 sloc) 1.949 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
<?php

use Zend\EventManager\EventManager;

define('ZF2_PATH',
    (getenv('ZF2_PATH') ? getenv('ZF2_PATH') : realpath(__DIR__ . '/library/Zend'))
);

require_once ZF2_PATH . '/Loader/StandardAutoloader.php';
$autoLoader = new Zend\Loader\StandardAutoloader();

// register our StandardAutoloader with the SPL autoloader
$autoLoader->register();

// register the Zend namespace
$autoLoader->registerNamespace('Zend', ZF2_PATH);

class ValidatePost
{
    public function validate($event)
    {
        $data = $event->getParams();
        
        if (!isset($data['title']) or !isset($data['slug'])) {
            throw new \InvalidArgumentException('Need a title and a slug!');
        }
        
        return $data;
    }
}

class SlugifyPost
{
    public function slugify($event)
    {
        $data = $event->getParams();
        
        $event->setParam('slug', strtolower(str_replace(' ', '-', $data['title'])));
        
        return $data;
    }
}

class Post
{
    protected $events = null;
    
    public function events()
    {
        if ($this->events === null) {
            $this->events = new EventManager(__CLASS__);
            
            $this->events->attach('save', array('SlugifyPost', 'slugify'), 100);
            $this->events->attach('save', array('ValidatePost', 'validate'), 90);
        }
        
        return $this->events;
    }
    
    public function save($data)
    {
        // this prepareArgs method allows to call the
        // setParam method in the MangleFoo::mangle method
        // so that ValidateFoo::isValid has the mangle'd data
        $this->events()->prepareArgs($data);
        $response = $this->events()->trigger('save', $this, $data);
        
        echo 'data saved! ' . json_encode($response->last());
    }
}

$post = new Post;

$values = array(
    'title' => 'My post'
);

try {
    $post->save($values);
} catch(\InvalidArgumentException $e) {
    echo $e->getMessage();
}
Something went wrong with that request. Please try again.