简体   繁体   English

在 zend-expressive-hal 配置中将选项传递给 ClassMethodsHydrator

[英]Pass options to ClassMethodsHydrator in zend-expressive-hal config

I use zend-expressive-hal (v3) and have the following config written for the delivery of my User class:我使用 zend-expressive-hal (v3) 并为交付我的用户 class 编写了以下配置:

return [
    [
        '__class__' => RouteBasedResourceMetadata::class,
        'resource_class' => Handler\User::class,
        'route' => 'users',
        'extractor' => ClassMethodsHydrator::class,
    ],
];

This works without any problems.这工作没有任何问题。 What I have noticed, however, is that the keys are stored in the generated JSON with underscores, while in my User class the methods are written camel case.然而,我注意到的是,密钥存储在生成的 JSON 中并带有下划线,而在我的用户 class 中,这些方法是用驼峰写成的。 How can I supplement my above configuration to pass options to the ClassMethodsHydrator class, eg underscoreSeparatedKeys = false?如何补充我的上述配置以将选项传递给 ClassMethodsHydrator class,例如 underscoreSeparatedKeys = false?

Aparently, I am not using the latest version of zend hydrator, so I don't have the Zend\Hydrator\ClassMethodsHydrator class.显然,我没有使用最新版本的 zend hydrator,所以我没有 Zend\Hydrator\ClassMethodsHydrator class。 I built my own hydrator (I know for sure that the objects have getters and setters for each property):我构建了自己的水合器(我确定对象的每个属性都有 getter 和 setter):

class ObjectWithGetterAndSetterHydrator extends AbstractHydrator
{

    public function extract($object)
    {
        if (!$object instanceof ApiEntityInterface) {
            throw new \RuntimeException('Could not extract object. Object must be instance of ' . ApiEntityInterface::class);
        }
        /** @var ApiEntityInterface $object */

        $properties = $object::getExportableProperties();
        $data       = [];
        foreach ($properties as $property) {
            $data[$property] = method_exists($object, 'get' . ucfirst($property)) ? $object->{'get' . ucfirst($property)}() : $object->{'is' . ucfirst($property)}();
        }

        return $data;
    }


    public function hydrate(array $data, $object)
    {
        foreach ($data as $key => $value) {
            $object->{'set' . ucfirst($key)}($value);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM