最初主题已启动here,但我需要一个有效的代码示例,如何使用Moo或Moose正确委派属性。
根据文档,我编写了这段代码来检查:
package Cat;
use Moo;
has 'token' => ( is => 'rw', default => '12345' );
has 'tiger' => ( is => 'rw', default => sub { my $self = shift; Cat::Tiger->new(token => $self->token) }, handles => [ qw(token) ] );
package Cat::Tiger;
use Moo;
extends 'Cat';
# + some additional methods
package main;
use Data::Dumper;
my $cat = Cat->new(token=>'54321');
warn $cat->token;
warn $cat->tiger->token;
但是这段代码会产生错误:
您无法用a覆盖本地定义的方法(令牌) 代表团在3.pl第5行
如果我在第5行删除handles => [ qw(token) ]
,代码将返回另一个错误:
3.pl第5行子程序“Tiger :: new”的深度递归。
那怎么办?
我需要将Cat::Tiger
对象($cat->tiger->token
)的标记设置为与Cat
对象($cat-token
)相同,并在每次Cat
标记时同步它们对象改变了。
答案 0 :(得分:2)
嗯,问题解决了将令牌移动到单独的类并使用MooX::Singleton用于此类:
package Credentials;
use Moo;
with 'MooX::Singleton';
has 'token' => ( is => 'rw', default => '12345' );
package Cat;
use Moo;
has 'credentials' => ( is => 'rw', default => sub { Credentials->instance }, handles => [qw(token)] );
has 'tiger' => ( is => 'rw', default => sub { Cat::Tiger->new(token => shift->token) } );
package Cat::Tiger;
use Moo;
has 'credentials' => ( is => 'rw', default => sub { Credentials->instance }, handles => [qw(token)] );
package main;
use Data::Dumper;
my $cat = Cat->new;
warn $cat->token;
warn $cat->tiger->token;
$cat->token('54321');
warn $cat->token;
warn $cat->tiger->token; # will be also 54321
如果有人知道更好的解决方案,欢迎您提出建议:)