1

我已经阅读了各种教程和Moo文档,但我找不到任何描述我想做的事情。

我想做的是如下所示:

has 'status' => (
  is  => 'ro',
  isa => Enum[qw(pending waiting completed)],
);

has 'someother' => (
  is       => is_status() eq 'waiting'   ? 'ro' : 'rw',
  required => is_status() eq 'completed' ? 1    : 0,
  isa      => Str,
  lazy     => 1,
);

如果我对这个想法不太了解,我将如何根据另一个属性的值来制作属性“ro”或“rw”并且是否需要?

请注意,枚举来自Type::Tiny

4

1 回答 1

2

问问自己为什么要这样做。您正在处理对象。这些是应用了一组逻辑的数据。该逻辑在类中描述,对象是应用了类逻辑的数据实例。

如果有一个属性(即数据)可以应用两种不同的逻辑,它是否仍然属于同一类?毕竟,属性是否可变是一个非常明确的规则。

所以你真的有两个不同的课程。一种someother属性是只读的,一种是可变的。

在 Moo(和 Moose)中,有几种方法可以构建它。

  • 实现 Foo::Static 和 Foo::Dynamic (或 Changeable 或其他),其中两者都是 Foo 的子类,并且只有一个属性更改
  • 实现 Foo 并实现一个子类
  • 实现 Foo 和改变 的行为的角色,someother并将其应用到构造函数中。Moo::Role继承自Role::Tiny

这是使用角色的方法的示例。

package Foo;
use Moo;
use Role::Tiny ();

has 'status' => ( is => 'ro', );

has 'someother' => (
    is      => 'ro',
    lazy    => 1,
);


sub BUILD {
  my ( $self) = @_;

  Role::Tiny->apply_roles_to_object($self, 'Foo::Role::Someother::Dynamic')
    if $self->status eq 'foo';
}

package Foo::Role::Someother::Dynamic;
use Moo::Role;

has '+someother' => ( is => 'rw', required => 1 );

package main;
use strict;
use warnings;
use Data::Printer;

# ...

首先,我们将创建一个具有动态someother.

my $foo = Foo->new( status => 'foo', someother => 'foo' );
p $foo;
$foo->someother('asdf');
print $foo->someother;

__END__
Foo__WITH__Foo::Role::Someother::Dynamic  {
    Parents       Role::Tiny::_COMPOSABLE::Foo::Role::Someother::Dynamic, Foo
    Linear @ISA   Foo__WITH__Foo::Role::Someother::Dynamic, Role::Tiny::_COMPOSABLE::Foo::Role::Someother::Dynamic, Role::Tiny::_COMPOSABLE::Foo::Role::Someother::Dynamic::_BASE, Foo, Moo::Object
    public methods (0)
    private methods (0)
    internals: {
        someother   "foo",
        status      "foo"
    }
}
asdf

如您所见,这是有效的。现在让我们做一个静态的。

my $bar = Foo->new( status => 'bar', someother => 'bar' );
p $bar;
$bar->someother('asdf');

__END__
Foo  {
    Parents       Moo::Object
    public methods (4) : BUILD, new, someother, status
    private methods (0)
    internals: {
        someother   "bar",
        status      "bar"
    }
}
Usage: Foo::someother(self) at /home/julien/code/scratch.pl line 327.

哎呀。一个警告。不像 Moose 那样是一个很好的“只读”异常,但我想这已经是最好的了。

但是,这对required属性没有帮助。你可以创建一个Foo->new( status => 'foo' )没有someother,它仍然会出来。

因此,您可能希望满足于子类方法或使用角色并构建工厂类

于 2015-08-24T15:28:35.147 回答