htfy96 / magic-transformer.php
PHP中的双向数组结构映射器
dev-master
2016-07-13 08:40 UTC
Requires
- php: >=5.3.4
This package is not auto-updated.
Last update: 2024-09-14 19:36:42 UTC
README
PHP中的双向数组结构映射器。
主动
模型转换在PHP项目中很常见。传统方式是编写A::transformToB
和A::setFromB
方法。然而,在大多数情况下,这两个方法背后的逻辑几乎相同,唯一的区别是一个构建对象,另一个从对象中提取信息。
然后是这个库:定义一次转换,双向使用。
用法
require_once 'magic_transformer.php'; use MagicTransform\M as M;
映射器是一个实现MagicTransform\iBidirectionTrans
接口的对象
interface iBidirectionTrans { public function forward_map($left_val); public function reverse_map($right_val, &$left_obj); }
//Define transformation $trans = M::make_mapper( [ 'abc' => M::$self[0], // the value of 'abc' is $left[0] 'ccc' => M::make_chain( M::$self[0], // The 2nd argument(which is a mapper) will receive $left[1] as $left [ 'yyy' => M::$self // Use self to reference $left ] ), 'ddd' => M::self['eee']['fff'], // to reference $left['eee']['fff'] 'eee' => M::make_chain( M::$self[2], // now $left(in make_list_mapper) is $left[2] M::make_list_mapper( // Apply the mapper to each item of list M::make_func_mapper( // customize mapper! function($left_val) { // forward return $left_val + 1; }, function ($right_val, &$left_obj) { $left_obj = $right_val - 1; } ) ) ) ] ); $left = ['0th', '1st', [1,2,3], 'eee' => ['fff' => 4]]; $right = $trans->forward_map($left); print_r($right); /* * Array ( [abc] => 0th [ccc] => Array ( [yyy] => 1st ) [ddd] => 4 [eee] => Array ( [0] => 2 [1] => 3 [2] => 4 ) */ // Now let's modify $right $right['abc'] = '0th0th'; $right['ccc']['yyy'] = ['1st1st']; $right['ddd'] = 100; $right['eee'][1] = 7; $left = array(); // You can use your ORM here! $trans->reverse_map($right, $left); print_r($left); /* Array ( [0] => 0th0th [1] => Array ( [0] => 1st1st ) [eee] => Array ( [fff] => 100 ) [2] => Array ( [0] => 1 [1] => 6 [2] => 3 ) ) */
就是这样!
API
以下所有API都在MagicTransform
命名空间中。
接口
iBidirectionTrans
interface iBidirectionTrans { public function forward_map($left_val); public function reverse_map($right_val, &$left_obj); }
所有映射器都必须实现此接口。
映射器/映射器制作
所有映射器制作器都在类M
中定义
make_key_mapper
映射$left[$key1][$key2]...
M::make_key_mapper('abc', 'def'); //$left['abc']['def']
__0/__1/__2/__3
make_key_mapper(0),...,make_key_mapper(3)的别名
self
一个总是返回自身且在调用时永远不会修改左侧值的映射器。
Magic函数[]作为make_key_mapper
的糖
make_chain
按顺序映射Arg1,Arg2,...,ArgN
M::make_chain(M::$__0, M::$__1); // $left[0][1], which is equivalent to make_key_mapper(0, 1)
make_list_mapper
接受一个映射器并将其应用于$left中的每个项目
M::make_list_mapper(M::$__0); //[$left[0][0], $left[1][0], ...]
make__func_mapper
自定义您自己的映射器。第一个参数是正向映射器,第二个是反向映射器。
M::make_func_mapper( // customize mapper! function($left_val) { // forward return $left_val + 1; }, function ($right_val, &$left_obj) { $left_obj = $right_val - 1; } ); // $left + 1
make_mapper
自动将简单数组转换为映射器。
转换应该使用此方法定义。
make_mapper( [ 'aaa' => M::$__0 ] );
许可证
Apache许可证。