我有一个很多层次的大哈希,我想把这个哈希变成一组 Moose 类。
哈希看起来像这样:
my %hash = (
company => {
id => 1,
name => 'CorpInc',
departments => [
{
id => 1,
name => 'Sales',
employees => [
{
id => 1,
name => 'John Smith',
age => '30',
},
],
},
{
id => 2,
name => 'IT',
employees => [
{
id => 2,
name => 'Lucy Jones',
age => '28',
},
{
id => 3,
name => 'Miguel Cerveza',
age => '25',
},
],
},
],
}
);
还有驼鹿类:
package Company;
use Moose;
has 'id' => (is => 'ro', isa => 'Num');
has 'name' => (is => 'ro', isa => 'Str');
has 'departments' => (is => 'ro', isa => 'ArrayRef[Company::Department]');
1;
package Company::Department;
use Moose;
has 'id' => (is => 'ro', isa => 'Num');
has 'name' => (is => 'ro', isa => 'Str');
has 'employees' => (is => 'ro', isa => 'ArrayRef[Company::Person]');
1;
package Company::Person;
use Moose;
has 'id' => (is => 'ro', isa => 'Num');
has 'first_name' => (is => 'ro', isa => 'Str');
has 'last_name' => (is => 'ro', isa => 'Str');
has 'age' => (is => 'ro', isa => 'Num');
1;
将此哈希转换为 Company 对象的最佳方法是什么?
到目前为止我考虑过的选项是:
- 手动循环 %hash,找到最深的“类”(例如 Person),首先创建这些,然后手动将它们添加到新创建的更高级别的类(部门)中,依此类推。
- 为每个类添加某种强制功能,这让我可以执行 Company->new(%hash) 之类的操作,并使每个类创建自己的“子类”(通过强制)
- 将 %hash 转换为类似于 MooseX::Storage 序列化的结构,然后使用 MooseX::Storage 为我实例化所有内容......
还有其他想法或建议吗?