<?php

/**
 * Abstract base model class
 * Implements the SplSubject interface
 * @author Jérome Brilland
 * @version 1.0
 * @copyright (c) 2009, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 * @abstract
 */
abstract class ModelBase implements SplSubject {

    /**
     * @var SplObjectStorage Observers
     * @access private
     */
    private $observers;

    /**
     * Class constructor
     * @access public
     */
    public function __construct() {
        $this->observers = new SplObjectStorage();
    }

    /**
     * Attaches an SplObserver so that it can be notified of updates.
     * @param SplObserver observer The SplObserver to attach.
     * @access public
     */
    public function attach( SplObserver $observer ) {
        $this->observers->attach( $observer );
    }

    /**
     * Detaches an observer from the subject to no longer notify it of updates.
     * @param SplObserver observer The SplObserver to detach.
     * @access public
     */
    public function detach( SplObserver $observer ) {
        $this->observers->detach( $observer );
    }

    /**
     * Notifies all attached observers.
     * @param string key Key
     * @access public
     */
    public function notify( $key = null, $arguments = null ) {
        $result = true;
        if ( !empty( $this->observers ) ) {
            foreach ( $this->observers as $observer ) {
                if ( !$observer->update( $this, $key ) ) {
                    $result = false;
                }
            }
        }
        return $result;
    }

}

?>