Notepad:PHP Test

From Amar
Revision as of 21:06, 22 May 2015 by Lax (talk | contribs)
Jump to navigationJump to search
 <?php

 /**
 * Event Bus Challenge
 * 
 * FIRST: COPY/PASTE ALL THIS CODE IN THE TEXTFIELD BELOW AND EDIT IT THERE
 * 
 * 1. The goal is to build a very simple PubSub/event class in PHP. 
 *    We will create an EventEmitter object and then we'll subscribe to events and trigger them. 
 *    Subscribing to an event simply adds a callback to be run when the event is triggered. 
 *    Triggering an event (emit) should run all the attached callbacks.
 * 2. Don't overthink it. The solution should only take a few minutes and a few lines of code. 
 *    Build only what you need to get the desired ouput.
 * 
 * Constraints:
 * 1. Although we only use error/success events, please build the class to handle arbitrary events.
 * 2. Events data will always be an associative array.
 * 3. A callback should always be safe to call.
 */

 class EventEmitter {

    var $current_callback;
    
    public function __construct() {
        // no special needs I can see
        $this->current_callback = array();
    }

    public function emit($description , $data) {
        // emit an message using previsouly subscribed function
        // loop through all the previous functions.
        if (!empty($this->current_callback[$description])) {
            foreach ($this->current_callback[$description] as $current) {
                call_user_func($current, $data);
            }
        }
    }

    public function subscribe($description, $callback_func_name) {
        // callback function specified. 
        // add to arrat
        if (empty($this->current_callback[$description])) {
            $this->current_callback[$description] = array();
        }
        $this->current_callback[$description][] = $callback_func_name;
    }

}

 $emitter = new EventEmitter;

 $error_callback = function($data) {
    echo "Error 1. {$data["message"]} \n";
 };

 $error_callback2 = function($data) {
    echo "Error 2. {$data["message"]} \n";
 };

 $success_callback = function($data) {
    echo "SUCCESS! {$data["message"]} \n";
 };

 $emitter->emit("error", ["message" => "Error one."]);

 $emitter->subscribe("error", $error_callback);
 $emitter->emit("error", ["message" => "Second error."]);

 $emitter->subscribe("error", $error_callback2);
 $emitter->emit("error", ["message" => "Yet another error."]);

 $emitter->subscribe("success", $success_callback);
 $emitter->emit("success", ["message" => "Great success!."]);

 // Expected output:

 // Error 1. Second error.
 // Error 1. Yet another error.
 // Error 2. Yet another error.
 // SUCCESS! Great success!