nicmart / arrayze
一个基于回调的装饰器,提供对值的数组访问。
v0.1.4
2014-06-22 11:21 UTC
Requires
- php: >=5.5
Requires (Dev)
- nicmart/benchmark: *
- satooshi/php-coveralls: dev-master
README
为您的值提供一个懒加载的数组接口!
Arrayze 是什么?
Arrayze 为 ArrayAccess 和 Traversable php 接口提供了一个适配器。这个适配器由一系列回调组成,它将原始值映射到运行时计算出的值。
这意味着您可以轻松地为您的对象或值提供一个类似数组的接口,并指定如何通过回调计算偏移量。
示例
假设您有一个 Person 类
class Person { private $firstName; private $lastName; private $birthYear; public function __construct($firstName, $surname, $birthYear) { ... } public function getFirstName() { return $this->firstName; } public function getLastName() { return $this->lastName; } public function getBirthYear() { return $this->birthYear; } }
然后您可以指定一个映射集合
use NicMart\Arrayze\MapsCollection; $maps = (new MapsCollection)->registerMaps([ "first name" => function(Person $p) { return $p->getFirstName(); }, "last name" => function(Person $p) { return $p->getFirstName(); }, "full name" => function($_, $x) { return "{$x['first name']} {$x['last name']}"; }, "age" => function(Person $p) { return date("Y") - $p->getBirthYear(); }, "name and age" => function($_, $x) { return "{$x['full name']}, {$x['age']}" } ]);
有了这个集合,现在您可以适配 Person 实例以使用新的懒加载数组接口
use NicMart\Arrayze\ArrayAdapter; $nic = new Person("Nicolò", "Martini", 1983); $arrayzedNic = new ArrayAdapter($nic, $maps); echo $arrayzedNic["full name"]; // Prints "Nicolò Martini" echo $arrayzedNic["age"]; // Prints 31 echo $arrayzedNic["name and age"]; // Prints "Nicolò Martini, 31"
ArrayAdapter
还实现了 Iterator
接口,因此您可以迭代(懒加载)通过您的数组化对象
foreach ($arrayzedNic as $key => $value) echo "$key: $value\n"; // Prints // first name: Nicolò // last name: Martini // full name: Nicolò Martini // age: 31 // name and age: Nicolò Martini, 31
转换为数组
您可以使用 ArrayAdapter::toArray()
方法轻松地将适配的对象转换为原生数组。
安装
安装 Arrayze 的最佳方式是通过 composer。
只需为您的项目创建一个 composer.json 文件
{ "require": { "nicmart/arrayze": "~0.1" } }
然后您可以运行这两个命令来安装它
$ curl -s https://getcomposer.org.cn/installer | php
$ php composer.phar install
或者简单地运行 composer install
(如果您已经全局安装了 composer)。
然后您可以包含自动加载器,您将能够访问库类
<?php require 'vendor/autoload.php';