americanreading / object-normalizer
对对象上的字段进行规范化
v1.1.0
2015-06-05 21:17 UTC
Requires
- php: >=5.3.0
Requires (Dev)
- phpunit/phpunit: ~4.6
This package is auto-updated.
Last update: 2024-09-19 10:04:57 UTC
README
特性
- 必需字段 必须存在于输出对象中,否则
normalize
抛出异常。 - 可选字段 如果存在,将被添加到输出对象中。
- 默认值 可以为字段提供默认值。
- 别名 允许您将输入对象上的字段名称映射到输出对象上的字段名称。
- 修改器可调用 改变字段值。
- 终结器可调用 允许在对象规范化后进行额外的修改。
示例
<?php
use AmericanReading\ObjectNormalizer\ObjectNormalizer;
// Begin with an array or object that contains fields we don't want and fields
// with the wrong names.
$input = [
"id" => 12852,
"show" => "Bob's Burger",
"character" => "Gene Belcher",
"favoriteColor" => "blue"
];
// Create a normalizer.
$normalizer = new ObjectNormalizer();
// Provide the names of the fields the final object should contain.
$normalizer->setRequiredFields(["name", "series")
// List other names for a field that may appear on the input object.
$normalizer->setAlias("name", ["character", "person"])
// Normalize using the settings provided above.
$output = $normalizer->normalize($input);
print_r($output);
/*
stdClass Object
(
[name] => Gene Belcher
[show] => Bob's Burger
)
*/
扩展示例
<?php
use AmericanReading\ObjectNormalizer\ObjectNormalizer;
$normalizer = new ObjectNormalizer();
$normalizer
->setRequiredFields(["name", "show"])
->setOptionalFields(["instrument", "favoriteColor", "favoriteAnimal"])
->setAlias("name", "character")
->setDefault("favoriteColor", "blue")
->setModifier("favoriteColor", function ($value) {
if ($value == "green") {
$value = "red";
}
return $value;
})
->setFinalizer(function ($obj) {
// Add an additional field, only for Gene.
if ($obj->name === "Gene Belcher") {
$obj->costume = "Beefsquatch";
}
return $obj;
});
$gene = [
"id" => 12852,
"show" => "Bob's Burgers",
"character" => "Gene Belcher",
"instrument" => "Casio Keyboard"
];
$normalGene = $normalizer->normalize($gene);
print_r($normalGene);
/*
stdClass Object
(
[name] => Gene Belcher
[show] => Bob's Burgers
[instrument] => Casio Keyboard
[favoriteColor] => blue
)
*/
$tina = [
"id" => 12853,
"show" => "Bob's Burgers",
"character" => "Tina Belcher",
"favoriteColor" => "green",
"favoriteAnimal" => "Horse"
];
$normalTina = $normalizer->normalize($tina);
print_r($normalTina);
/*
stdClass Object
(
[name] => Tina Belcher
[show] => Bob's Burgers
[favoriteColor] => red
[favoriteAnimal] => Horse
)
*/