承接 paysera/lib-normalization 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

paysera/lib-normalization

Composer 安装命令:

composer require paysera/lib-normalization

包简介

Library for normalizing and denormalizing PHP objects to and from JSON structures

README 文档

README

Build Status Coverage Status Quality Score Total Downloads Latest Stable Version PHP Version Require License

This library allows to de/normalize your business entities (plain PHP objects) without tightly coupling them with your normalization format. You would usually do this before converting normalized structure to JSON or after converting from it.

If you intend to use the library with Symfony, use lib-normalization-bundle instead.

Why?

Symfony has Serializer component that has normalizers as a part of it. This component is created for similar reasons but with different approach.

Symfony component exposes your business entities by default, but allows sophisticated but challenging configuration options. It also writing custom normalization logic, but it usually resides inside your normalized classes (which probably are plain PHP objects).

Paysera Normalization library embraces simplicity by always writing a bit of code for getting full control of the situation – normalization logic is placed in related classes, which are usually registered from DIC. This allows to use other services, fetch data from database, call remote services if needed or make any other things in familiar PHP source code. You can easily rename any fields, use any custom naming, duplicate some data for backward compatibility or, well, just write any other code. No difficult configuration is needed for edge-cases, as you have full control over the situation.

Main features of this library:

  • supports explicit type safety when denormalizing by integrating lib-object-wrapper;
  • normalization type can be guessed by passed data;
  • easily reuse other de/normalizers without direct dependencies;
  • supports different normalization groups with fallback to default one;
  • supports explicitly or implicitly included fields, allowing performance tuning in normalization process.

Installation

composer require paysera/lib-normalization

Usage

Basic usage

Write de/normalizers for your business entities:

<?php

// ...

class ContactDetailsNormalizer implements NormalizerInterface, ObjectDenormalizerInterface, TypeAwareInterface
{
    public function getType(): string
    {
        return ContactDetails::class;
    }

    /**
     * @param ContactDetails $data
     * @param NormalizationContext $normalizationContext
     *
     * @return array
     */
    public function normalize($data, NormalizationContext $normalizationContext)
    {
        return [
            'email' => $data->getEmail(),
            // will automatically follow-up with normalization by guessed types:
            'residence_address' => $data->getResidenceAddress(),
            'shipping_addesses' => $data->getShippingAddresses(),
        ];
    }

    public function denormalize(ObjectWrapper $data, DenormalizationContext $context)
    {
        return (new ContactDetails())
            ->setEmail($data->getRequiredString('email'))
            ->setResidenceAddress(
                $context->denormalize($data->getRequiredObject('residence_address'), Address::class)
            )
            ->setShippingAddresses(
                $context->denormalizeArray($data->getArrayOfObject('shipping_addesses'), Address::class)
            )
        ;
    }
}
<?php

// ...

class AddressNormalizer implements NormalizerInterface, ObjectDenormalizerInterface, TypeAwareInterface
{
    private $countryRepository;
    private $addressBuilder;

    // ...

    public function getType(): string
    {
        return Address::class;
    }

    /**
     * @param Address $data
     * @param NormalizationContext $normalizationContext
     *
     * @return array
     */
    public function normalize($data, NormalizationContext $normalizationContext)
    {
        return [
            'country_code' => $data->getCountry()->getCode(),
            'city' => $data->getCity(),
            'full_address' => $this->addressBuilder->buildAsText($data->getStreetData()),
        ];
    }

    public function denormalize(ObjectWrapper $data, DenormalizationContext $context)
    {
        $code = $data->getRequiredString('country_code');
        $country = $this->countryRepository->findOneByCode($code);
        if ($country === null) {
            throw new InvalidDataException(sprintf('Unknown country %s', $code));
        }   

        return (new Address())
            ->setCountry($country)
            ->setCity($data->getRequiredString('city'))
            ->setStreetData(
                $this->addressBuilder->parseFromText($data->getRequiredString('full_address'))
            )
        ;
    }
}

Register all de/normalizers in the provider:

<?php

$provider = new GroupedNormalizerRegistryProvider();
$provider->addTypeAwareNormalizer(new ContactDetailsNormalizer());
$provider->addTypeAwareNormalizer(new AddressNormalizer(/* ... */));

Create needed services:

$coreDenormalizer = new CoreDenormalizer($provider);
$coreNormalizer = new CoreNormalizer($provider, new TypeGuesser(), new DataFilter());

Use for de/normalization:

// must be stdClass, not array
$data = json_decode('{
    "email":"a@example.com",
    "residence_address":{"country_code":"LT","city":"Vilnius","full_address":"Park street 182b-12"},
    "shipping_addresses":[]
}');
$contactDetails = $coreDenormalizer->denormalize($data, ContactDetails::class);

$normalized = $coreNormalizer->normalize($contactDetails);

var_dump($normalized);
// object(stdClass)#1 (3) { ...

For advanced usage please also see lib-normalization-bundle and the source code.

If you have any questions, feel free to create an issue.

Semantic versioning

This library follows semantic versioning.

See Symfony BC rules for basic information about what can be changed and what not in the API.

Running tests

composer update
composer test

Contributing

Feel free to create issues and give pull requests.

You can fix any code style issues using this command:

composer fix-cs

paysera/lib-normalization 适用场景与选型建议

paysera/lib-normalization 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 18.56k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2018 年 10 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 paysera/lib-normalization 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 paysera/lib-normalization 我们能提供哪些服务?
定制开发 / 二次开发

基于 paysera/lib-normalization 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 18.56k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 6
  • 依赖项目数: 3
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 2
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-10-10