Last active
April 17, 2017 09:23
-
-
Save viankakrisna/be114a823466197fa43106cd74bfdf4f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Store { | |
/** | |
* @var array | |
*/ | |
public $state = []; | |
/** | |
* @param $reducer | |
* @param array $initialState | |
* @param $middleware | |
*/ | |
public function __construct( $reducer, $initialState = [] ) { | |
$this->reducer = $reducer; | |
$this->state = $initialState; | |
} | |
/** | |
* @param $action | |
*/ | |
public function dispatch( $action = [] ) { | |
$this->state = call_user_func( | |
$this->reducer, | |
$this->state, | |
$action | |
); | |
} | |
/** | |
* @return mixed | |
*/ | |
public function getState() { | |
return $this->state; | |
} | |
/** | |
* @param $cb | |
*/ | |
public function subscribe( $cb ) { | |
array_push( $this->subscribers, $cb ); | |
return function () { | |
array_splice( $this->subscribers, array_search( $cb, $this->subscribers ), 1 ); | |
}; | |
} | |
} | |
$store = new Store( function ( $state, $action ) { | |
switch ( $action['type'] ) { | |
case 'INCREMENT': | |
$state['counter'] = $state['counter'] + 1; | |
return $state; | |
case 'DECREMENT': | |
$state['counter'] = $state['counter'] - 1; | |
return $state; | |
default: | |
return $state; | |
} | |
}, [ | |
'counter' => 0, | |
] ); | |
$store->dispatch( ['type' => $_GET['action']] ); | |
$state = $store->getState(); | |
var_dump( $state['counter'] ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment