跳到内容

如何创建自定义名称转换器

编辑此页

序列化器组件使用名称转换器来转换属性名称(例如,从 JSON 中的 snake_case 转换为 PHP 属性的 CamelCase)。

假设您有以下对象

1
2
3
4
5
6
7
namespace App\Model;

class Company
{
    public string $name;
    public string $address;
}

在序列化形式中,所有属性必须以 org_ 为前缀,如下所示

1
{"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}

自定义名称转换器可以处理这种情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace App\Serializer;

use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class OrgPrefixNameConverter implements NameConverterInterface
{
    public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string
    {
        // during normalization, add the prefix
        return 'org_'.$propertyName;
    }

    public function denormalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string
    {
        // remove the 'org_' prefix on denormalizing
        return str_starts_with($propertyName, 'org_') ? substr($propertyName, 4) : $propertyName;
    }
}

7.1

通过 normalize()denormalize() 访问当前类名、格式和上下文是在 Symfony 7.1 中引入的。

注意

您还可以实现 AdvancedNameConverterInterface 以访问当前类名、格式和上下文。

然后,配置序列化器以使用您的名称转换器

1
2
3
4
5
# config/packages/serializer.yaml
framework:
    serializer:
        # pass the service ID of your name converter
        name_converter: 'App\Serializer\OrgPrefixNameConverter'

现在,当在应用程序中使用序列化器时,所有属性都将以 org_ 为前缀

1
2
3
4
5
6
7
// ...
$company = new Company('Acme Inc.', '123 Main Street, Big City');

$json = $serializer->serialize($company, 'json');
// {"org_name": "Acme Inc.", "org_address": "123 Main Street, Big City"}
$companyCopy = $serializer->deserialize($json, Company::class, 'json');
// Same data as $company
这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本