如何在Moose中定义默认属性属性值?

时间:2010-12-15 16:36:10

标签: perl moose

正如标题所暗示的那样,我希望能够在课堂上做到这样的事情:

use MooseX::Declare;

class MyClass {
    default_attribute_propeties(
        is       => 'ro',
        lazy     => 1,
        required => 1,
    );

    has [qw( some standard props )] => ();

    has 'override_default_props' => (
        is       => 'rw',
        required => 0,
        ...
    );

    ...
}

即,定义一些默认属性值,这些属性值将应用于所有属性定义,除非被覆盖。

1 个答案:

答案 0 :(得分:3)

听起来您想要编写一些自定义属性声明,它们提供了一些默认选项。这在Moose::Cookbook::Extending::Recipe1中有所涉及,例如:

package MyApp::Mooseish;

use Moose ();
use Moose::Exporter;

Moose::Exporter->setup_import_methods(
    install     => [ qw(import unimport init_meta) ],
    with_meta   => ['has_table'],
    also        => 'Moose',
);

sub has_table
{
    my ($meta, $name, %config) = @_;

    $meta->add_attribute(
        $name,

        # overridable defaults.
        is => 'rw',
        isa => 'Value', # any defined non-reference; hopefully the caller
                        # passed their own type, which will override
                        # this one.
        # other options you may wish to supply, or calculate based on
        # other arguments passed to this function...

        %config,
    );
}

然后在你的班上:

package MyApp::SomeObject;

use MyApp::Moosish;

has_table => (
    # any normal 'has' options;
    # will override the defaults.
);

# remaining class definition as normal.