makasim/values

替身对象。构建模型、API客户端等的高效方式

0.5.3 2019-06-10 11:13 UTC

This package is auto-updated.

Last update: 2024-08-25 06:07:53 UTC


README

formapro\values是一个MIT许可的开源项目,其持续发展完全由社区和我们的客户支持。如果您想加入他们,请考虑

Build Status

您的“替身”对象

这种方法试图从数组和对象世界中汲取最佳之处。因此,使用此库,您可以像平时一样处理对象,但内部一切都被存储为数组。数组很容易从对象中检索或设置。

可用于

对象为我们提供了一个易于信赖的合约。我们可以为类添加类型提示,对其方法使用自动完成。这是好事,但用数据填充对象或获取它们的当前状态既不容易也不便宜。我们提供了各种工具,如序列化程序、转换器等。当我们必须处理对象树时,情况变得更糟。

数组另一方面很容易存储或发送。每次您调用API或对数据库进行查询时,最终都会处理一个数组。这是一个优势,但它不提供任何合约,当数组结构发生变化时,代码很容易被破坏。

示例

获取仓库信息示例

让我们使用Github API来获取Symfony仓库的信息。这是实际响应,我们将使用简化的版本。

<?php
namespace Acme;

use Formapro\Values\ValuesTrait;
use Formapro\Values\ObjectsTrait;
use function Formapro\Values\set_values;

class Repo
{
    use ValuesTrait;
    use ObjectsTrait;

    public function getStargazersCount()
    {
        return $this->getValue('stargazers_count');
    }

    /** @return Owner */
    public function getOwner()
    {
        return $this->getObject('owner', Owner::class);
    }
}

class Owner
{
    use ValuesTrait;

    public function getId()
    {
        return $this->getValue('id');
    }

    public function getLogin()
    {
        return $this->getValue('login');
    }
}

$data = json_decode('
{
  "id":458058,
  "name":"symfony",
  "full_name":"symfony/symfony",
  "owner":{
    "login":"symfony",
    "id":143937,
  },
  "stargazers_count":13945,
}
', true);

$repo = new Repo();
set_values($repo, $data);

$repo->getStargazersCount(); // 13945
$repo->getOwner()->getLogin(); // symfony

创建新gist

现在,让我们创建一个新的gist。根据Github API,我们必须发送一个包含文件集合的对象。让我们创建Gist和GistFile对象。用数据填充它们并将它们作为数组获取。

<?php
namespace  Acme;

use Formapro\Values\ObjectsTrait;
use Formapro\Values\ValuesTrait;

class Gist
{
    use ValuesTrait;
    use ObjectsTrait;

    public function setDescription($description)
    {
        $this->setValue('description', $description);
    }

    public function setPublic($bool)
    {
        $this->setValue('public', $bool);
    }

    public function addFile($fileName, GistFile $file)
    {
        $this->addObject('files', $file, $fileName);
    }
}

class GistFile
{
    use ValuesTrait;

    public function __construct($content)
    {
        $this->setValue('content', $content);
    }
}

$file = new GistFile('String file contents');

$gist = new Gist();
$gist->setDescription('the description for this gist');
$gist->setPublic(true);
$gist->addFile('file1.txt', $file);

get_values($gist);

/*
[
    'description' => 'the description for this gist',
    'public' => true,
    'files' => [
        'file1.txt' => [
            'content' => 'String file contents',
        ]
    ]
]
 */

// now you can send it to api. 

由Forma-Pro开发

Forma-Pro是一家全栈开发公司,其兴趣也扩展到开源开发。作为一个强大的专业团队,我们旨在通过在电子商务、Docker和面向微服务的架构领域开发尖端解决方案来帮助社区,这些领域我们已经积累了多年的经验。我们的主要专业领域是基于Symfony框架的解决方案,但我们总是寻找允许我们以最佳方式完成工作的技术。我们致力于创建能够革新架构和可扩展性的开发方式的解决方案。

如果您对我们开源开发、此产品特别是其他事项有任何疑问和咨询,请随时通过opensource@forma-pro.com联系我们

许可

本软件遵循MIT许可证发布。