formapro/values

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

0.5.1 2019-02-01 08:10 UTC

This package is auto-updated.

Last update: 2024-08-29 04:54:39 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许可证下发布的。