Jorge Niedbalski R : Another boring unix programmer.

Jorge Niedbalski R.

Patrones : Observer (PHP5)

leave a comment »

Cuando

Se utiliza cuando se tiene una arquitectura del tipo un productor a varios consumidores ( cliente-servidor ) , es la primitiva mas esencial del paso de mensajes, acoplamiento en una dirección y accionamiento jerarquico para un modelo de eventos.

Como

Código

En este caso utilizaremos la capa de abstracción de streams de PHP5 para desplegar un ejemplo de la implementación de este patrón.

<?php
/**
* PHP5 Observer pattern
*
* @author Jorge Niedbalski R.
* @(#)Data::Observer
*
**/
define('DEFAULT_SOCKET_TIMEOUT', 30);

class   SubjectException extends Exception {}
class   Subject {

    private $observerCollection = array();

    public  function    registerObserver(Observer $observer) 
    {
        $object_hash = spl_object_hash($observer);
        
        if(array_key_exists($object_hash, $this->observerCollection) == TRUE) {
            throw new SubjectException("Object %s already exists\n", $object_hash);
        }
    
        $this->observerCollection[$object_hash] = $observer;
        return ( TRUE );
    }

    public  function    unregisterObserver(Observer $observer) 
    {
         unset($this->observerCollection[spl_object_hash($observer)]);
    }
    
    public  function    notifyObservers($message) 
    {
        foreach($this->observerCollection as $key => $registered_observer) {
            $registered_observer->notify($message);

        }
    }

}

class  Observer {
    public  function    notify($message) {
        $context = stream_context_create(array(
            'http' => array(
                            'method' => 'POST',
                            'header' => sprintf("Authorization: Basic %s\r\nContent-type: application/x-www-form-urlencoded\r\n", base64_encode(sprintf("%s:%s", $this->username, $this->password))),
                            'content'=> http_build_query(array('status' => $message)),
                            'timeout'=> DEFAULT_SOCKET_TIMEOUT,
                      ),
            )
        ); 

        file_get_contents($this->endpoint, FALSE,$context);
    }
}


class   TwitterObserver  extends Observer {
        public  function    __construct() {
            $this->endpoint = "http://twitter.com/statuses/update.xml";
            $this->username = "ikslabdein";
            $this->password = "foobar";
        }
}

class   OtherObserver extends Observer {
        public  function    __construct() {
            $this->endpoint = "http://other.service.com/update.xml";
            $this->username = "foobar";
            $this->password = "bafoor";
        }

}


$subject  = new Subject();

$subject->registerObserver(new TwitterObserver());
$subject->notifyObservers("I am Testing observer pattern, yeah !@#");


?>

Otros

El ejemplo describe un patrón de observer en PHP5 para hacer POST via HTTP de un dato a multiples destinos. Puede ser ampliable a multiples stream asincronos o a algún otro protocolo implementado como stream wrapper..

Referencias
Wikipedia- Observer Pattern

Advertisement

Written by niedbalski

23/05/2010 at 7:18 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.