Moose:将参数注入构造中

发布于 2024-11-29 16:15:39 字数 494 浏览 1 评论 0原文

我有一个附加了验证的文件名属性。现在,当在构造过程中未指定文件名时,我想从配置文件中读取它。

subtype 'filename'
        => as 'Str'
        => where { -r $_ }
        => message { "$_ is not a readable file" };

has 'students_file' => ( is => 'rw', isa => 'filename', default => '' );
has 'teachers_file' => ( is => 'rw', isa => 'filename', default => '' );

问题是 BUILD 似乎是在验证发生后运行的。 BUILDARGS 的所有示例似乎都处理构造对象的不同方式。

那么我应该在哪里读取配置并设置属性呢?

I have a filename attribute that has attached validation. Now when the filename isn't specified during construction I want to read it from a configuration file.

subtype 'filename'
        => as 'Str'
        => where { -r $_ }
        => message { "$_ is not a readable file" };

has 'students_file' => ( is => 'rw', isa => 'filename', default => '' );
has 'teachers_file' => ( is => 'rw', isa => 'filename', default => '' );

The issue is that BUILD seems to be run after the validation occurs. All examples of BUILDARGS seem to handle a different way of constructing the object.

So where should I read the configuration and set the attribute?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温折酒 2024-12-06 16:15:39

提供从配置文件设置它们的 teachers_filestudents_file builder 方法(或内联 default 子函数)。仅当这些属性未作为构造函数的键提供时,构建器才会运行(除非您使用 init_arg => undef 来阻止在构造函数中设置它们) 。

如果您的配置是其自己的属性,并且具有读取配置文件的构建器,那么您在 configteachers_filestudents_file 之间存在排序问题代码>.您可以通过使 teachers_filestudents_file 惰性属性来解决此问题,这确保它们不会尝试在 config 属性之前构造。但是,您可能希望确保在构造过程中尽早抛出“foo 不是可读文件”错误,而不是在第一次使用该属性时抛出。 解决这个问题。

sub BUILD {
  my $self = shift;
  $self->teachers_file;
  $self->students_file;
}

您可以通过添加确保在构造函数返回之前读取(并构造)这些属性一次来

Give teachers_file and students_file builder methods (or inline default subs) that set them from the config file. The builder will only run if those attributes aren't provided as keys to the constructor (unless you use init_arg => undef to prevent them from being set in the constructor).

If your config is an attribute of its own, with a builder that reads the config file, then you have an ordering problem between config and teachers_file and students_file. You can resolve this by making teachers_file and students_file lazy attributes, which ensures that they won't try to be constructed before the config attribute. However, you may want to make sure that the "foo is not a readable file" error is thrown as early as possible during construction, instead of the first time the attribute is used. You can work around that by adding

sub BUILD {
  my $self = shift;
  $self->teachers_file;
  $self->students_file;
}

which ensures that those attributes are read once (and constructed) before the constructor returns.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文