2014-02-25 77 views
2

有兩個組件:test.mc我需要調用組件name.mi中定義的兩種方法。如何調用Mason組件中定義的多個方法?

組件/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不工作,給這個錯誤:

Can't use string ("MC0::name_mi") as a HASH ref while "strict refs" in use at accessor MC0::name_mi::name (defined at /.../testpoet/comps/name.mi line 2) line 5

的問題:

  • 誰能告訴我一個例子,如何正確使用$m->load($path)
  • 爲什麼不能從showname method訪問$.name - 那麼,如何調用name.mi組件中定義的多個方法?

例如,與想要實現的東西在純perl的什麼都(schematicaly)寫入下一個:

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; 

回答

3

使用construct而不是load

From 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 %> 
+0

THANK YOU VERY MUCH! :) – kobame

相關問題