/// Declare mini-framework skeleton
class Model {
var $id, $data;
function __construct($id){
$this->id = $id;
}
function name(){
return $this->data['name'];
}
}
class Dataset {
static function get($id){
$mock_data = [
123 => ['name' => 'Vasya Pupkin'],
456 => ['name' => 'Petya Zalupkin'],
];
$model_obj = new Model($id);
$model_obj->data = $mock_data[$id];
return $model_obj;
}
}
class Transform {
function up($arg){
return strtoupper($arg);
}
function down($arg){
return strtolower($arg);
}
}
class Cache {
private static $instance = null;
protected $data = [];
function try($key, $fn){
if (!array_key_exists($key, $this->data)){
$this->data[$key] = $fn();
}
return $this->data[$key];
}
static function instance(){
if (is_null(self::$instance)){
self::$instance = new self;
}
return self::$instance;
}
}
class Context {
function __construct(){
$this->transform = new Transform;
$this->cache = Cache::instance();
}
function with_cache($key, $fn){
return $this->cache->try($key, $fn);
}
}
//// Define actions
$foo = function(){
$item = Dataset::get(123);
$name = $this->cache->try(123,
function() use($item) {
return $this->transform->up($item->name());
}
);
return $name;
};
$bar = function(){
$item = Dataset::get(456);
$this->with_cache(456,
function() use($item, &$name) {
return $name = $this->transform->down($item->name());
}
);
return $name;
};
//// Imitate HTTP queries
print $foo->call(new Context)."<br>\n"; // some request
print $bar->call(new Context)."<br>\n"; // other request
//// Dump shared object
print_r(Cache::instance());
вернёт:
VASYA PUPKIN
petya zalupkin
Cache Object ( [data:protected] => Array ( [123] => VASYA PUPKIN [456] => petya zalupkin ) )
То есть,
- описываем экшны в форме анонимных функций, не привязанных к какому-либо классу
- выполняем их каждую в изолированном контексте. В пхп в принципе не актуально, но для standalone-приложений необходимо
- легко и естественно работаем с shared-объектами, передавая им в лямбдах тот же, какой использовали бы и без них (пример с кэшем, не используем многословную схему if ($cache->exists()){ ...get_cache... } else { ...create_value... ...save_value... }).
не всё полезно, что в swap полезло