__END__ =pod =head1 NAME Poet::Manual::Tutorial - Poet tutorial =head1 DESCRIPTION This tutorial provides a tour of Poet by showing how to build a sample web application - specifically a micro-blog, which seems to be a popular "hello world" for web frameworks. :) Thanks to L and L for the inspiration. =head1 INSTALLATION First we install Poet and a few other support modules. If you don't yet have cpanminus (C), get it L. Then run cpanm -S --notest DateTime DBD::SQLite Poet Rose::DB::Object Omit the "-S" if you don't have root, in which case cpanminus will install Poet and prereqs into C<~/perl5>. Omit the "--notest" if you want to run all the installation tests. Note that this will take about four times as long. =head1 SETUP You should now have a C app installed: % which poet /usr/local/bin/poet Run this to create the initial environment: % poet new Blog blog/.poet_root blog/bin/app.psgi blog/bin/get.pl ... Now run 'blog/bin/run.pl' to start your server. The name of the app, C, will be used in app-specific class names. It is also used for the default directory name (C), though you can move that wherever you want. Run this to start your server: % blog/bin/run.pl and you should see something like Running plackup --Reload ... --env development --port 5000 Watching ... for file updates. HTTP::Server::PSGI: Accepting connections at http://0:5000/ and you should be able to hit that URL to see the Poet welcome page. In Poet, your entire web site lives within a single directory hierarchy called the I. It contains subdirectories for configuration, libraries, Mason components (templates), static files, etc. From now on, every file we create in this tutorial is assumed to be under the environment root. =head1 DATA LAYER (MODEL) For any website it's a good idea to have a well-defined, object-oriented I through which you retrieve and change data. Poet and Mason don't have much to say about how you do this, so we'll make some minimal reasonable choices here and move on. For this demo we'll represent blog articles with a single sqlite table. Create a file C with: create table if not exists articles ( id integer primary key autoincrement, content string not null, create_time timestamp not null, title string not null ); Then run % cd blog % sqlite3 -batch data/blog.db < db/schema.sql We'll use L to provide a nice object-oriented API to our data (L would work as well). Create a file C to tell Rose how to connect to our database: lib/Blog/DB.pm: package Blog::DB; use Poet qw($poet); use strict; use warnings; use base qw(Rose::DB); __PACKAGE__->use_private_registry; __PACKAGE__->register_db( driver => 'sqlite', database => $poet->data_path("blog.db"), ); 1; and a file C to represent the articles table: lib/Blog/Article.pm: package Blog::Article; use Blog::DB; use strict; use warnings; use base qw(Rose::DB::Object); __PACKAGE__->meta->setup( table => 'articles', auto => 1, ); __PACKAGE__->meta->make_manager_class('articles'); sub init_db { Blog::DB->new } 1; Basically this gives us =over =item * a C class with a constructor for inserting articles and instance methods for each of the columns, and =item * a C class (autogenerated) for searching for and retrieving multiple articles =back See L for more information. =head1 QUICK VARS AND UTILITIES In C above, we have use Poet qw($poet); followed by database => $poet->data_path("blog.db"), C<$poet> is the global L object, providing information about the environment and its directory paths. We use it here to get the full path to our sqlite database, without having to hardcode our environment root. More generally C<$poet> is one of several special Poet "quick vars" that can be imported into any package, just by including it on the C line. Another important one is C<$conf>, which gives you access to configuration: use Poet qw($conf $poet); ... my $value = $conf->get('key', 'default'); You can also import sets of utilities in the same way, e.g. ':file' for file utilities and ':web' for web-related utilities. See L for the full list of Poet vars and utility sets. =head1 CONFIGURATION Poet configuration files are kept in the C subdirectory. The files are in L form and are merged in a particular order to create a single configuration hash. For this tutorial we can ignore everything but C. It currently contains: layer: development server.port: 5000 This says that you are in development mode (so that you'll see errors directly in the browser, etc.) and running on port 5000. You'll need to add one more entry: server.load_modules: - Blog::Article This says to load C, our model, on server startup. See L for More information on configuration. =head1 MASON PAGES AND COMPONENTS Mason is the templating engine that you'll use to render pages (the I), and is also responsible for routing URLs to specific pieces of code (the I). So it's not surprising that most of the rest of this tutorial will focus on Mason. Mason's basic building block is the I - a file with a mix of Perl and HTML. All components lives under the subdirectory C; this is known in Mason parlance as the L. Given a URL, Mason will dispatch to a L. This component decides the overall page layout, and then may call other components to fill in the details. C generated a few starter components for us, but we're not going to use those, so let's clear them by running rm -fR comps; mkdir comps Now here's our first component to serve the home page, C: comps/index.mc: 1 2 3 4 My Blog: Home 5 6 7 8

Welcome to my blog.

9 10 <& all_articles.mi &> 11 12 Add an article 13 14 15 Any component with a C<.mc> extension is considered a top-level component. C is a special path - it will match the URI of its directory, in this case '/'. (For more special paths and details on how Mason finds page components, see L.) Most of this component contains just HTML, which will be output exactly as written. The single piece of special Mason syntax here is 10 <& all_articles.mi &> This is a L - it invokes another component, whose output is inserted in place. =head2 %-lines, substitution tags, <%init> blocks Next we create C. Because it has an C<.mi> extension rather than C<.mc>, it is an L rather than a top-level component, and cannot be reached by an external URL. It can only be reached via a component call from another component. comps/all_articles.mi 1 % if (@articles) { 2 Showing <% scalar(@articles) %> article<% @articles > 1 ? "s" : "" %>. 3
    4 % foreach my $article (@articles) { 5
  • <& article/display.mi, article => $article &>
  • 6 % } 7
8 % } 9 % else { 10

No articles yet.

11 % } 12 13 <%init> 14 my @articles = @{ Blog::Article::Manager->get_articles 15 (sort_by => 'create_time DESC') }; 16 Three new pieces of syntax here: =over =item Init block The L%initE|Mason::Manual::Syntax/E%initE> block on lines 13-16 specifies a block of Perl code to run first when this component is called. In this case it fetches and sorts the list of articles into a lexical variable C<< @articles >>. =item %-lines L<%-lines|Mason::Manual::Syntax/PERL LINES> - lines beginning with a single '%' - are treated as Perl rather than HTML. They are especially good for loops and conditionals. =item Substitution tags This line 2 Showing <% scalar(@articles) %> article<% @articles > 1 ? "s" : "" %>. shows two L. Code within C<< <% >> and C<< %> >> is treated as a Perl expression, and the result of the expression is output in place. =back We see another component call here, C<< article/display.mi >>, which displays a single article; we pass the article object in a name/value argument pair. Components can be in different directories and component paths can be relative or absolute. =head2 Attributes Next we create C. (It is in a new subdirectory, showing that you can freely organize components among different directories.) comps/article/display.mi: 1 <%class> 2 use Date::Format; 3 my $date_fmt = "%A, %B %d, %Y %I:%M %p"; 4 has 'article' => (required => 1); 5 6 7
8

<% $.article->title %>

9

<% $.article->create_time->strftime($date_fmt) %>

10 <% $.article->content %> 11
The L%classE|Mason::Manual::Syntax/E%classE> block on lines 1-4 specifies a block of Perl code to place near the top of the generated component class, outside of any methods. This is the place to use modules, declare permanent constants/variables, declare attributes with 'has', and define helper methods. Most components of any complexity will probably have a C<< <%class> >> section. On line 4 we declare a single incoming attribute, C
. It is I, meaning that if C had forgotten to pass it, we'd get a fatal error. Throughout this component, we refer to the article attribute via the expression $.article This not-quite-valid-Perl syntax is transformed behind the scenes to $self->article and is one of the rare cases in Mason where we create new syntax on top of Perl, because we want attributes and method calls to be as convenient as possible. The transformation itself is performed by the L, which is in the L list but can be omitted if the source filtering offends you. :) =head2 Content wrapping, autobases, inheritance, method modifiers Now we have to handle the URL C, linked from the home page. We do this with our second page component, C. It contains only HTML (for now). comps/new_article.mc: 1 2 3 4 My Blog: Home 5 6 7 8

Add an article

9 10
11

Title:

12

Text:

13 14

15
16 17 18 Notice that C and C have the same outer HTML template; other pages will as well. It's going to be tedious to repeat this everywhere. And of course, we don't have to. We take the common pieces out of the C and C and place them into a new component called C: comps/Base.mc: 1 <%augment wrap> 2 3 4 5 My Blog 6 7 8 <% inner() %> 9 10 11 When any page in our hierarchy is rendered, C will get control first. It will render the upper portion of the template (lines 2-7), then call the specific page component (line 8), then render the lower portion of the template (lines 9-10). Now, we can remove everything but the inside of the C<< >> tag from C and C. comps/index.mc:

Welcome to my blog.

<& all_articles.mi &> Add an article comps/new_article.mc

Add an article

Title:

Text:

More details on how content wrapping works L. =head2 Form handling, pure-perl components C posts to C
. Let's create a component to handle that, called C. It will not output anything, but will simply take action and redirect. comps/article/publish.mp: 1 has 'content'; 2 has 'title'; 3 4 method handle () { 5 my $session = $m->session; 6 if ( !$.content || !$.title ) { 7 $session->{message} = "Content and title required."; 8 $session->{form_data} = $.args; 9 $m->redirect('/new_article'); 10 } 11 my $article = Blog::Article->new( 12 title => $.title, 13 content => $.content, 14 create_time => DateTime->now( time_zone => 'local' ) 15 ); 16 $article->save; 17 $session->{message} = sprintf( "Article '%s' saved.", $.title ); 18 $m->redirect('/'); 19 } The C<.mp> extension indicates that this is a L component. Other than the 'package' and 'use Moose' lines that are generated by Mason, it looks just like a regular Perl class. You could accomplish the same thing with a C<.mc> component containing a single C<< <%class> >> block, but this is easier and more self-documenting. On lines 1 and 2 we declare incoming attributes. Because this is a top-level page component, the attributes will be populated with our POST parameters. On line 4 we define a C method to validate the POST parameters, create the article, and redirect. C is one of the L that Mason calls initially on all top-level page components; the default just renders the component's HTML as we've seen before. Defining C is the way to take an action without rendering anything, which is perfect for form actions. (It's always better to redirect after a form action than to display content directly.) The C keyword comes from L, which is imported into components by default; see L. On line 5 we grab the Plack session via C<< $m->session >>. This is one of a handful of L only available in Poet. On lines 7 and 17, we set a message in the session that we want to display on the next page. Rather than just making this work for a specific page, let's add generic code to the template in C: comps/Base.mc: 7 => 8 % if (my $message = delete($m->session->{message})) { => 9
<% $message %>
=> 10 % } 11 <% inner() %> 12 Now, any page can place a message in the session, and it'll appear on just the next page. On line 8, we place the POST data in the session so that we can repopulate the form with it - we'll do that in the next chapter. C<< $.args >> is a special component attribute that contains all the arguments passed to the component. =head2 Filters We need to change C<< comps/new_article.mc >> to repopulate the form with the submitted values when validation fails. comps/new_article.mc: 1

Add an article

2 ==> 3 % $.FillInForm($form_data) {{ 4
5

Title:

6

Text:

7 8

9
==> 10 % }} 11 ==> 12 <%init> ==> 13 my $form_data = delete($m->session->{form_data}); ==> 14 On lines 3 and 10 we surround the form with a I. A filter takes a content block as input and returns a new content block which is output in its place. In this case, the C filter uses L to fill in the form from the values in C<$form_data>. Mason has a few built-in filters, and others are provided in plugins; for example C is provided in the L. Another common filter provided by this plugin is C, or C for short. We ought to use this in C when displaying the article title, in case it has any HTML-unfriendly characters in it:

<% $.article->title |H %>

See L for more information about using, and creating, filters. =head1 POET SCRIPTS Up til now all our code has been in Mason components. Now let's say we want to create a I to purge blog entries older than a configurable number of days. The script, of course, will need access to the same Poet features as our components. Run this from anywhere inside your environment: % poet script purge_old_entries.pl ...bin/purge_old_entries.pl Poet created a stub script for us inside C. Let's take a look: #!/usr/local/bin/perl use Poet::Script qw($conf $poet); use strict; use warnings; Line 2 of the script initializes the Poet environment. This means Poet does several things: =over =item * Searches upwards from the script for the environment root (as marked by the C<.poet_root> file). =item * Reads and parses your configuration. =item * Unshifts onto @INC the lib/ subdirectory of your environment, so that you can C your application modules. =item * Imports the specified quick vars - in this case C<$conf> and C<$poet> - into the script namespace. See L. =back Poet initialization has to happen exactly once per process, before any Poet features are used. In fact, take a look at C -- which was generated for you initially -- and you'll see that it does 'use Poet::Script' as well. This initializes Poet for the entire web environment. Now we can fill out our purge script: #!/usr/local/bin/perl use Poet::Script qw($conf); use Blog::Article; use strict; use warnings; my $days_to_keep = $conf->get( 'blog.days_to_keep' => 365 ); my $min_date = DateTime->now->subtract( days => $days_to_keep ); Blog::Article::Manager->delete_articles( where => [ create_time => { lt => $min_date } ] ); In line 2, we've eliminated the unneeded C<$poet>. In line 7, we get C<$days_to_keep> from configuration, giving it a reasonable default if there's nothing in configuration. Finally in lines 8-10 we delete articles less than the minimum date. =head1 FILES FROM THIS TUTORIAL The final set of files for our blog demo are in the C directory of the Poet distribution, or you can view them at L. =head1 SEE ALSO L =head1 AUTHOR Jonathan Swartz =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2012 by Jonathan Swartz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut