Moose(Perl):访问基类中的属性定义

Lum*_*umi 7 perl moose

使用__PACKAGE__->meta->get_attribute('foo'),您可以访问foo给定类中的属性定义,这可能很有用.

#!perl
package Bla;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 1;
no Moose; __PACKAGE__->meta->make_immutable;

package Blub;
use Moose;
has bla => is => 'ro', isa => 'Str';
has hui => is => 'ro', isa => 'Str', required => 0;
no Moose; __PACKAGE__->meta->make_immutable;

package Blubbel;
use Moose;
extends 'Blub';
no Moose; __PACKAGE__->meta->make_immutable;

package main;
use Test::More;
use Test::Exception;

my $attr = Bla->meta->get_attribute('hui');
is $attr->is_required, 1;

$attr = Blub->meta->get_attribute('hui');
is $attr->is_required, 0;

$attr = Blubbel->meta->get_attribute('hui');
is $attr, undef;
throws_ok { $attr->is_required }
  qr/Can't call method "is_required" on an undefined value/;
diag 'Attribute aus Basisklassen werden hier nicht gefunden.';

done_testing;
Run Code Online (Sandbox Code Playgroud)

但是,正如这个小代码示例所证明的那样,这不能用于访问基类中的属性定义,这对我的特定情况更有用.有没有办法实现我想要的?

hob*_*bbs 9

注意,get_attribute不要搜索超类,因为您需要使用它find_attribute_by_name

- Class :: MOP :: Class docs.确实这段代码通过了:

my $attr = Bla->meta->find_attribute_by_name('hui');
is $attr->is_required, 1;

$attr = Blub->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;

$attr = Blubbel->meta->find_attribute_by_name('hui');
is $attr->is_required, 0;
Run Code Online (Sandbox Code Playgroud)