

__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<Dancer|Dancer::Tutorial> and
L<Flask|https://github.com/mitsuhiko/flask/tree/master/examples/flaskr/> for
the inspiration.

=head1 INSTALLATION

First we install Poet and a few other support modules.

If you don't yet have cpanminus (C<cpanm>), get it
L<here|http://search.cpan.org/perldoc?App::cpanminus#INSTALLATION>. 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<poet> 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<Blog>, will be used in app-specific class names. It is
also used for the default directory name (C<blog>), 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<environment>. 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<model> 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<db/schema.sql> 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<Rose::DB::Object> to provide a nice object-oriented API to our data
(L<DBIx::Class> would work as well). Create a file C<lib/Blog/DB.pm> 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<lib/Blog/Article.pm> 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<Blog::Article> class with a constructor for inserting articles and instance
methods for each of the columns, and

=item *

a C<Blog::Article::Manager> class (autogenerated) for searching for and
retrieving multiple articles

=back

See L<Rose::DB::Object::Tutorial> for more information.

=head1 QUICK VARS AND UTILITIES

In C<lib/Blog/DB.pm> above, we have

    use Poet qw($poet);

followed by

    database => $poet->data_path("blog.db"),

C<$poet> is the global L<Poet::Environment|Poet::Environment> 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<use Poet> 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<Poet::Import|Poet::Import> for the full list of Poet vars and utility sets.

=head1 CONFIGURATION

Poet configuration files are kept in the C<conf> subdirectory. The files are in
L<YAML|http://www.yaml.org/> form and are merged in a particular order to
create a single configuration hash.

For this tutorial we can ignore everything but C<conf/local.cfg>. 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<Blog::Article>, our model, on server startup.

See L<Poet::Conf|Poet::Conf> for More information on configuration.

=head1 MASON PAGES AND COMPONENTS

Mason is the templating engine that you'll use to render pages (the I<view>),
and is also responsible for routing URLs to specific pieces of code (the
I<controller>). 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<component> - a file with a mix of Perl
and HTML. All components lives under the subdirectory C<comps>; this is known
in Mason parlance as the L<component root|Mason::Manual::Components/The
component root and component paths>.

Given a URL, Mason will dispatch to a L<top-level
component|Mason::Manual::Components/Component file extensions>. This component
decides the overall page layout, and then may call other components to fill in
the details.

C<poet new> 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>:

  comps/index.mc:

     1  <html>
     2    <head>
     3      <link rel="stylesheet" href="/static/css/blog.css">
     4      <title>My Blog: Home</title>
     5    </head>
     6    <body>
     7    
     8      <h2>Welcome to my blog.</h2>
     9  
    10      <& all_articles.mi &>
    11  
    12      <a href="/new_article">Add an article</a>
    13  
    14    </body>
    15  </html>

Any component with a C<.mc> extension is considered a top-level component.
C<index.mc> 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<Mason::Manual::RequestDispatch>.)

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<component call|Mason::Manual::Components/CALLING COMPONENTS> - it
invokes another component, whose output is inserted in place.

=head2 %-lines, substitution tags, <%init> blocks

Next we create C<comps/all_articles.mi>. Because it has an C<.mi> extension
rather than C<.mc>, it is an L<internal|Mason::Manual::Components/Component
file extensions> 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  <b>Showing <% scalar(@articles) %> article<% @articles > 1 ? "s" : "" %>.</b>
     3  <ul class="articles">
     4  %   foreach my $article (@articles) {
     5    <li><& article/display.mi, article => $article &></li>
     6  %   }
     7  </ul>
     8  % }
     9  % else {
    10  <p>No articles yet.</p>
    11  % }
    12  
    13  <%init>
    14  my @articles = @{ Blog::Article::Manager->get_articles
    15      (sort_by => 'create_time DESC') };
    16  </%init>

Three new pieces of syntax here:

=over

=item Init block

The L<E<lt>%initE<gt>|Mason::Manual::Syntax/E<lt>%initE<gt>> 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  <b>Showing <% scalar(@articles) %> article<% @articles > 1 ? "s" : "" %>.</b>

shows two L<substitution tags|Mason::Manual::Syntax/SUBSTITUTION TAGS>. 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<comps/article/display.mi>. (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  </%class>
     6  
     7  <div class="article">
     8    <h3><% $.article->title %></h3>
     9    <h4><% $.article->create_time->strftime($date_fmt) %></h4>
    10    <% $.article->content %>
    11  </div>

The L<E<lt>%classE<gt>|Mason::Manual::Syntax/E<lt>%classE<gt>> 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<article>. It is
I<required>, meaning that if C<all_articles.mi> 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<DollarDot
plugin|Mason::Plugin::DollarDot>, which is in the L<default
plugins|Mason::PluginBundle::Default> 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</new_article>, linked from the home page. We do
this with our second page component, C<comps/new_article.mc>. It contains only
HTML (for now).

  comps/new_article.mc:

     1  <html>
     2    <head>
     3      <link rel="stylesheet" href="/static/css/blog.css">
     4      <title>My Blog: Home</title>
     5    </head>
     6    <body>
     7  
     8      <h2>Add an article</h2>
     9  
    10      <form action="/article/publish" method=post>
    11        <p>Title: <input type=text size=30 name=title></p>
    12        <p>Text:</p>
    13        <textarea name=content rows=20 cols=70></textarea>
    14        <p><input type=submit value="Publish"></p>
    15      </form>
    16  
    17    </body>
    18  </html>

Notice that C<comps/index.mc> and C<comps/new_article.mc> 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<comps/index.mc> and C<comps/new_article.mc> and place them into a new
component called C<comps/Base.mc>:

  comps/Base.mc:

     1  <%augment wrap>
     2    <html>
     3      <head>
     4        <link rel="stylesheet" href="/static/css/mwiki.css">
     5        <title>My Blog</title>
     6      </head>
     7      <body>
     8        <% inner() %>
     9      </body>
    10    </html>
    11  </%augment>

When any page in our hierarchy is rendered, C<comps/Base.mc> 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<< <body> >> tag from
C<comps/index.mc> and C<comps/new_article.mc>.

  comps/index.mc:

    <h2>Welcome to my blog.</h2>
    
    <& all_articles.mi &>
    
    <a href="/new_article">Add an article</a>
   
  comps/new_article.mc

    <h2>Add an article</h2>
    
    <form action="/article/publish" method=post>
      <p>Title: <input type=text size=30 name=title></p>
      <p>Text:</p>
      <textarea name=content rows=20 cols=70></textarea>
      <p><input type=submit value="Publish"></p>
    </form>

More details on how content wrapping works L<here|Mason::Component/wrap>.

=head2 Form handling, pure-perl components

C</new_article.mc> posts to C</article/publish>. Let's create a component to
handle that, called C<comps/article/publish.mp>. 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<pure-perl|Mason::Manual::Components/Component file extensions> 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<handle> method to validate the POST parameters, create
the article, and redirect. C<handle> is one of the L<structural
methods|Mason::Component/STRUCTURAL METHODS> 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<handle> 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<method> keyword comes from L<Method::Signatures::Simple>, which is
imported into components by default; see L<Mason::Component::Moose>.

On line 5 we grab the Plack session via C<< $m->session >>. This is one of a
handful of L<web-related methods|Poet::Mason/NEW REQUEST METHODS> 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<Base.mc>:

  comps/Base.mc:

     7      <body>
 =>  8  % if (my $message = delete($m->session->{message})) {
 =>  9        <div class="message"><% $message %></div>
 => 10  % }      
    11        <% inner() %>
    12      </body>

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  <h2>Add an article</h2>
      2  
 ==>  3  % $.FillInForm($form_data) {{
      4  <form action="/article/publish" method=post>
      5    <p>Title: <input type=text size=30 name=title></p>
      6    <p>Text:</p>
      7    <textarea name=content rows=20 cols=70></textarea>
      8    <p><input type=submit value="Publish"></p>
      9  </form>
 ==> 10  % }}
     11  
 ==> 12  <%init>
 ==> 13  my $form_data = delete($m->session->{form_data});
 ==> 14  </%init>

On lines 3 and 10 we surround the form with a I<filter>. 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<FillInForm> filter uses
L<HTML::FillInForm|HTML::FillInForm> 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<FillInForm> is provided in the L<HTMLFilters
plugin|Mason::Plugin::HTMLFilters>.

Another common filter provided by this plugin is C<HTMLEscape>, or C<H> for
short. We ought to use this in C</article/display.mi> when displaying the
article title, in case it has any HTML-unfriendly characters in it:

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

See L<Mason::Manual::Filters> 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<cron script> 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<bin>. 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<use> your application modules.

=item *

Imports the specified quick vars - in this case C<$conf> and C<$poet> - into
the script namespace. See L<Poet::Import|Poet::Import>.

=back

Poet initialization has to happen exactly once per process, before any Poet
features are used. In fact, take a look at C<bin/run.pl> -- 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<eg/blog> directory of the
Poet distribution, or you can view them at
L<github|https://github.com/jonswar/perl-poet/tree/master/eg/blog>.

=head1 SEE ALSO

L<Poet|Poet>

=head1 AUTHOR

Jonathan Swartz <swartz@pobox.com>

=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
