Skip to content

Instantly share code, notes, and snippets.

@viankakrisna
Last active April 17, 2017 09:23
Show Gist options
  • Save viankakrisna/be114a823466197fa43106cd74bfdf4f to your computer and use it in GitHub Desktop.
Save viankakrisna/be114a823466197fa43106cd74bfdf4f to your computer and use it in GitHub Desktop.
<?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