有两个组件:test.mc
我需要调用组件name.mi
中定义的两个方法。
组件/name.mi
<%class>
has 'name';
</%class>
<%method text>
<pre>Some text here</pre>
</%method>
<%method showname>
NAME: <% $.name %>
</%method>
组件/test.mc
<%init>
my $namecomp = $m->load('name.mi', name=>'john');
</%init>
<% $namecomp->text %>
<% $namecomp->showname %>
运行/test.mc
:
$namecomp->text
方法工作。$namecomp->showname
NOT无效,发出此错误:当“严格参考”时,不能使用字符串(“MC0 :: name_mi”)作为HASH参考 在访问器MC0 :: name_mi :: name中使用(在 /.../testpoet/comps/name.mi第2行第5行
问题:
$m->load($path)
?$.name
访问showname method
- 那么,如何调用name.mi
组件中定义的多个方法?package Myapp::Name;
has 'name';
method text() {
print "some text";
}
method showname {
print "Name: " . $self->name();
}
并将其用作:
my $namecomp = Myapp::Name->new( name => 'John' );
$namecomp->text;
$namecomp->showname;
答案 0 :(得分:3)
使用construct
代替load
来自perldoc Mason::Request
:
load (path) Makes the component path absolute if necessary, and calls Interp load to load the component class associated with the path.
...
construct (path[, params ...]) Constructs and return a new instance of the component designated by path params, if any, are passed to the constructor. Throws an error if path does not exist.
当构造将加载时,加载不会返回可用对象。
以下内容适用于/test.mc
:
<%init>
my $namecomp = $m->construct('name.mi', name=>'john');
</%init>
<% $namecomp->text %>
<% $namecomp->showname %>