gnugat / marshaller
v2.0.0
2015-05-30 10:16 UTC
Requires
- php: >=5.3.3
Requires (Dev)
- fabpot/php-cs-fixer: ~1.6
- memio/spec-gen: ~0.2
- phpspec/phpspec: ~2.2
- phpunit/phpunit: >=3.7,<5.0
This package is auto-updated.
Last update: 2022-02-01 12:47:44 UTC
README
一个PHP库,用于将一种格式转换为另一种格式。
Marshaller不会尝试猜测如何转换给定的输入,而是依赖于开发者实现的MarshallerStrategies
:它使我们完全控制输出格式。
要自动将输入转换为特定格式(如XML、JSON或YAML),可能最好使用其他工具(例如JMS Serializer)。
安装
Marshaller可以使用Composer进行安装
composer require "gnugat/marshaller:~2.0"
简单转换
让我们以以下对象为例
<?php class Article { public function __construct($title, $content) { $this->title = $title; $this->content = $content; } public function getTitle() { return $this->title; } public function getContent() { return $this->content; } } $article = new Article('Nobody expects...', '... The Spanish Inquisition!');
如果我们想将其转换为以下格式
// ... array( 'title' => 'Nobody expects...', 'content' => '... The Spanish Inquisition!', );
那么我们首先需要创建一个MarshallerStrategy
// ... require __DIR__.'/vendor/autoload.php'; use Gnugat\Marshaller\MarshallerStrategy; class ArticleMarshaller implements MarshallerStrategy { public function supports($toMarshal, $category = null) { return $toMarshal instanceof Article; } public function marshal($toMarshal) { return array( 'title' => $toMarshal->getTitle(), 'content' => $toMarshal->getContent(), ); } }
第二步是在Marshaller
中注册它
// ... use Gnugat\Marshaller\Marshaller; $marshaller = new Marshaller(); $marshaller->add(new ArticleMarshaller());
最后,我们可以实际转换对象
// ... $marshalledArticle = $marshaller->marshal($article);
部分转换
如果我们需要将Article
转换为以下部分格式
// ... array('title' => 'Nobody expects...');
那么我们首先需要定义一个新的MarshallStrategy
// ... class PartialArticleMarshaller implements MarshallStrategy { public function supports($toMarshal, $category = null) { return $toMarshal instanceof Article && 'partial' === $category; } public function marshal($toMarshal) { return array( 'title' => $toMarshal->getTitle(), ); } }
由于这个MarshallerStrategy
的support
条件更严格,我们希望在ArticleMarshaller
之前进行检查。这可以通过将PartialArticleMarshaller
注册为比ArticleMarshaller
更高的优先级(在这种情况下,优先级高于0)来实现。
// ... $marshaller->add(new PartialArticleMarshaller, 1);
最后,我们可以调用Marshaller
,针对partial
类别
$marshaller->marshal($article, 'partial');
集合转换
为了避免这种情况
// ... $articles = array($article); foreach ($articles as $article) { $marshaller->marshal($article); }
我们可以使用以下快捷方法
// ... $marshaller->marshalCollection($articles);
更多文档
您可以使用以下方式查看当前和过去的版本
git tag
命令- GitHub上的发布页面
- 显示版本之间变更的文件
您可以在以下链接中找到更多文档