2

有两个组件: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 ref 而在访问器 MC0::name_mi::name 中使用“strict refs”(在 /.../testpoet/comps/name.mi 第 2 行定义) 第 5 行

问题:

  • 谁能告诉我一个如何正确使用的例子$m->load($path)
  • 为什么不能访问 from-$.name那么showname method,如何调用name.mi组件中定义的多个方法呢?

例如,想要实现纯 perl 中可以(示意性地)写成的东西:

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;
4

1 回答 1

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.

Load 不会返回可用的对象,而Construct 会。

以下对我有用/test.mc

<%init>
        my $namecomp = $m->construct('name.mi', name=>'john');
</%init>
<% $namecomp->text %>
<% $namecomp->showname %>
于 2014-02-25T21:23:29.960 回答