由于从Http请求过来的参数,数量不定、没有默认值,构建指定的类对象有些麻烦。
参数越多,解析赋值越多。
解析的包:parse-to-object/parse-to-object,可以更简洁的构造指定的对象。

要求

php >= 8.2

安装

composer require parse-to-object/parse-to-object

使用

use ParseToObject\ParseToObject;
use ParseToObject\ParseAttr;
 
enum TestType: int {
    case Normal = 0;
    case Api = 1;
}
 
class TestSubOject {
    #[ParseAttr]
    public int $id;
    #[ParseAttr]
    public ?string $name;
}
 
class TestOject {
    #[ParseAttr(name: "id")]
    public int $id;
    #[ParseAttr]
    public ?string $name;
    #[ParseAttr]
    public $age;
    #[ParseAttr]
    public TestType $type = TestType::Normal;
    #[ParseAttr(name: "sub")]
    public ?TestSubOject $subOject = null;
    #[ParseAttr(className: TestSubOject::class)]
    public array $subList = [];
    #[ParseAttr]
    public array $numberList = [];
    #[ParseAttr(name: "delimiterStr", sourceType: "delimiter-str", delimiter: "|")]
    public array $delimiterList = [];
    #[ParseAttr(name: "jsonStr", sourceType: "json-str")]
    public ?TestSubOject $jsonObj = null;
    
    public int $sex;
 
    use ParseToObject;
}
$sub = [
    'id' => 11,
    'name' => 'TestSub'
];
$params = [
    'id' => 1,
    'name' => 'Test',
    'age' => 20,
    'type' => 1,
    'sub' => $sub,
    'subList' => [
        [
            'id' => 12,
            'name' => 'TestSub12'
        ],
        [
            'id' => 13,
            'name' => 'TestSub13'
        ]
    ],
    'numberList' => [1, 2, 3],
    'delimiterStr' => 'a|b|c',
    'jsonStr' => json_encode($sub),
];
$testOject = TestOject::from($params);
or
ParseToObject\Parser::make(TestOject::class, $params)->convertToObject();

另类执念
0 声望0 粉丝

生活百般滋味,人生需要笑对。