2017 © Pedro Peláez
 

library observers

A basic implementation of the observer pattern in PHP

image

michaelking0/observers

A basic implementation of the observer pattern in PHP

  • Saturday, September 10, 2016
  • by MichaelKing0
  • Repository
  • 1 Watchers
  • 0 Stars
  • 7 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 3 Versions
  • 0 % Grown

The README.md

Build Status Code Climate SensioLabsInsight, (*1)

Basic PHP observer pattern implementation

Usage

Installation

composer require michaelking0/observers

Making a class Observable (the subject)

In your subject class, implement the MichaelKing0\Observers\Interfaces\ObservableInterface interface. Also, use the trait MichaelKing0\Observers\Traits\ObservableTrait., (*2)

<?php

namespace ACME;

use MichaelKing0\Observers\Interfaces\ObservableInterface;
use MichaelKing0\Observers\Traits\ObservableTrait;

class MySubject implements ObservableInterface
{
    use ObservableTrait;
}

Then just add a function that uses the notify method, (*3)

<?php

namespace ACME;

use MichaelKing0\Observers\Interfaces\ObservableInterface;
use MichaelKing0\Observers\Traits\ObservableTrait;

class MySubject implements ObservableInterface
{
    use ObservableTrait;

    public function save()
    {
        $this->notify('SubjectSaved');
    }
}

This will notify an observers of the event, and pass the event name and current instance as an argument, (*4)

Creating an Observer

To create an observer, implement the MichaelKing0\Observers\Interfaces\ObservableInterface interface., (*5)

<?php

namespace ACME;

use MichaelKing0\Observers\Interfaces\ObservableInterface;
use MichaelKing0\Observers\Interfaces\ObserverInterface;

class MyObserver implements ObserverInterface
{
    public function update($event, ObservableInterface $observable)
    {
        echo 'It works!';
    }
}

Attaching an observer

You can attach an observer to a subject by calling the attach method with the event name, and observer instance i.e., (*6)

$subject = new MySubject();
$subject->attach('SubjectSaved', new MyObserver());

The Versions

10/09 2016

dev-master

9999999-dev

A basic implementation of the observer pattern in PHP

  Sources   Download

MIT

The Development Requires

by Michael King

10/09 2016

0.1.1

0.1.1.0

A basic implementation of the observer pattern in PHP

  Sources   Download

MIT

The Development Requires

by Michael King

10/09 2016

0.1

0.1.0.0

A basic implementation of the observer pattern in PHP

  Sources   Download

MIT

The Development Requires

by Michael King