phpfluent / arraystorage
1.4.0
2014-09-07 19:44 UTC
Requires (Dev)
- phpmd/phpmd: ~2.0
- phpunit/phpunit: ~4.2
- squizlabs/php_codesniffer: ~1.5
README
将数组用作数据库的非持久化方法。
安装
该软件包可在Packagist上找到,您可以使用Composer进行安装。
composer require phpfluent/arraystorage
用法
以下示例使用文件开头以下使用声明
use PHPFluent\ArrayStorage\Storage;
创建并返回一个集合
$storage = new Storage(); $storage->users; // This is a collection
将记录插入到集合中
您可以使用一个单个数组
$storage = new Storage(); $storage->users->insert(['name' => 'Henrique Moody']);
但是您也可以使用记录对象
use PHPFluent\ArrayStorage\Record; $storage = new Storage(); $record = new Record(); $record->name = 'Henrique Moody'; $storage->users->insert($record);
您可以从存储对象创建记录对象
$storage = new Storage(); $record = $storage->users->record(); // You also can provide default data, like an array or stdClass $record->name = 'Henrique Moody'; $storage->users->insert($record);
一个重要的要点是,在将记录插入到提供给记录的集合对象后,它会给记录一个唯一的(递增整数)id
属性。
从集合中删除记录
$storage = new Storage(); $storage->users->delete(['name' => 'Henrique Moody']);
从集合中删除所有记录
$storage = new Storage(); $storage->users->delete();
在集合中查找多个记录
$storage->users->findAll(['status !=' => false]); // Return an Collection object with the partial result (if any)
在集合中查找单个记录
$storage->users->find(['priority >=' => 4]); // Return an Record object with the first matched result (if any) or NULL
使用标准对象
$criteria = $storage->users->criteria(); $criteria->foo->equalTo(2) ->bar->in([1, 2, 3]) ->baz->regex('/^[0-9]{3}$/') ->qux->like('This _s spart%') ->quux->iLike('tHiS _S sPaRt%') ->corge->between(array(1, 42)) ->grault->lessThan(1000) ->garply->greaterThan(0) ->waldo->notEqualTo(false) ->fred->greaterThanOrEqualTo(13); $storage->users->find($criteria);
将数据转换为其他格式
有时您想要将数据转换为其他格式,为此我们提供了转换器。
转换器接受任何实现Traversable接口的对象,由于Record
、Collection
和Storage
类实现了此接口,因此您可以将它们中的任何一个转换为其他格式。
以下示例假设您有以下use
声明
use PHPFluent\ArrayStorage\Converter;
Arr
将数据转换为数组。
$converter = new Converter\Arr(); $converter->convert($storage->collectionName); // Returns an array with the records as array too
如果您不希望转换对象的子代(也实现Traversable接口的值),您只需在转换器构造函数中定义一个标志,例如
$converter = new Converter\Arr(false); $converter->convert($storage->collectionName); // Returns an array of Record objects
Json
将数据转换为JSON格式。
$converter = new Converter\Json(); $converter->convert($storage->collectionName); // Returns an string with the JSON
您也可以在转换器构造函数中定义json_encode()选项,例如
$converter = new Converter\Json(JSON_NUMERIC_CHECK); $converter->convert($storage->collectionName); // Returns the JSON but encodes numeric strings as numbers
我们使用默认选项JSON_PRETTY_PRINT
。
Xml
将数据转换为XML格式。
$converter = new Converter\Xml(); $converter->convert($storage->collectionName); // Returns an string with the XML