Just read the Poet::Import.
Simple example:
# generate app My
poet new my
cd my
add a class My::Import
, e.g.
vi lib/My/Import.pm
and add into it
package My::Import;
use Poet::Moose;
extends 'Poet::Import';
use Types::Path::Tiny qw(Path);
# create some variable
has 'mytemp' => (is => 'ro', isa => Path, coerce => 1, default => '/tmp');
method provide_var_mytemp ($caller) { #your WANTED variable name - add after the "provide_var_"
return $self->mytemp;
}
1; #happy perl
e.g. the Poet::Import
already importing variables $conf
and $env
(and also the utility tag :web
. So, you just extends the Poet::Import
, by adding another "attribute" (your "variable") into it.
In the above example
- added the attribute
mytemp
- and want call the global variable as
$mytemp
.
Now, you can use it for example in your components. Edit your comps/index.mc
.
Into the top add
<%class>
use Poet qw($mytemp); #your global variable (is a Path::Tiny object to /tmp)
</%class>
and add following too:
<h1>My files in the /tmp</h1>
<pre>
% for my $file ($mytemp->children) {
<% $file %>
% }
</pre>
The $mytemp
using the use Poet qw($mytemp);
is imported from your My/Import.pm
. (it is read-only, by it's definition - (is => 'ro',...
).
Everything in the Poet/Mason
is Moose
:), so (of course) you can import rw
variable with any isa
... etc.
Just remember, the above is true global and persistent variable. E.g. its content is preserved between requests. In most cases you don't want use such variables, only in few special cases, for example, you want initialise some database handle $dbh
(what should be available util the application runs) and such.
Second, here is also the $m->notes
method, but don't over-use it. From the docs:
The notes() method provides a place to store application data between
components - essentially, a hash which persists for the duration of
the request.
Consider storing this kind of data in a read-write attribute of the
page component.
Mostly, it is enough to use simple component attributes, e.g. see for example in the generated default app the usage of the $.title
(e.g. $self->title).
Or you just can pass variables to components as arguments,
<& somecomp.mc, arg1 => 'some', arg2 => 'other' &>
and so on...
Again, every component
is:
- just a camel
- with antlers
- using some masonry tools
- in poetic environment
- at the top of the PSGI hill
:)
Poet::Import
and theprovide_var_varname
method. – Microanalysis