guennichi/property-loader

PHP 库,用于动态加载对象属性

v2.2.1 2021-02-17 13:23 UTC

This package is auto-updated.

Last update: 2024-09-19 18:49:32 UTC


README

Build Status Coverage Status

A PHP library to dynamically load object properties using custom handlers (useful for DTO's). It comes with two ClassMetadata mapping loaders.

  • StaticMethodLoader: Load mapping configuration using configurePropertyLoaderMetadata() method.
  • AnnotationLoader: Load mapping configuration using annotations existed on src/Loaders/ directory

安装

推荐使用 Composer 安装 property-loader

# Install Composer
$ curl -sS https://getcomposer.org/installer | php

接下来,运行 Composer 命令以安装 ibanfirst-sdk 的最新稳定版本。

$ composer require guennichi/property-loader

安装完成后,您需要引入 Composer 的自动加载器

require 'vendor/autoload.php';

用法

本库的入口点是 Guennichi\PropertyLoader 类。

$mappingLoader = new Guennichi\PropertyLoader\Mapping\Loader\AnnotationLoader(
    new Doctrine\Common\Annotations\AnnotationReader()
);

$propertyLoader = new Guennichi\PropertyLoader\PropertyLoader($mappingLoader);

创建自定义属性加载器

创建加载器

您可以通过扩展基本抽象加载器类 Guennichi\PropertyLoader\Loader 来创建自定义加载器。这样做后,您将能够管理您的自定义加载器如何在给定对象内部加载属性。

作为一个例子,您将创建一个基本的属性加载器,它会在人对象的一个属性中动态生成一个电子邮件地址。

/**
 * @Annotation
 * @Target("PROPERTY")
 */
class Email extends Guennichi\PropertyLoader\Loader {
    // The source property name
    // Which we will use to generate the email
    // based on it's value.
    public string $source;
}
创建加载器处理器

如你所见,加载器类相当简单。实际的处理由另一个“约束验证器”类执行。约束验证器类由约束的 handledBy() 方法指定,它具有以下默认逻辑

// in the base Guennichi\PropertyLoader\Loader class
public function handledBy(): string
{
    return static::class.'Handler';
}

换句话说,如果你创建了一个自定义加载器(例如 Email),PropertyLoader 库将在实际加载时自动查找另一个类,即 EmailHandler

处理器类只有一个必需的方法 handle(),有关处理器更详细的信息,请参阅 guennichi/property-loader-bundle 包。

使用新的加载器
namespace App\DTO;

use App\Loaders as AcmeLoad;

class Person
{
    // ...

    public string $name;
    
    /**
     * @AcmeLoad\Email(source="name") 
     */
    public string $email;
    // ...
}

如你所见,我们在 Person 类中添加了新的自定义加载器,在我们的例子中,我们希望根据 "name" 属性的值加载 "email" 属性。

现在,让我们看看我们的 Person 对象的情况如何

$person = new Person();
$person->name = 'radhi';

// Load properties based on mappings and stored handlers
$propertyLoader->load($person, function (Email $emailLoader, ExecutionContextInterface $context {
        // Get the sourceProperty reflection object
        // based on "source" (name of property)
        $sourceProperty = $context->getClassMetadata()
        ->getReflectionClass()
        ->getProperty($emailLoader->source);
        
        $object = $context->getObject();

        $value = $sourceProperty->getValue($object) . '@guennichi.com';

        $context->getPropertyMetadata()->setPropertyValue($value, $object);
});


echo $person->email; // radhi@guennichi.com

支持 PHP >= 7.4

此客户端库仅支持 PHP 版本 >= 7.4,有关更多信息,请参阅 支持版本

有问题吗?

如果您有任何问题,请 创建一个问题

许可证

此库在 MIT 许可证下发布。有关详细信息,请参阅捆绑的 LICENSE 文件。