Amon2 6.13 documentation

Tutorial - Create BBS site

Tutorial - Create BBS site

Create skeleton

Just type:

% amon2-setup.pl BBS
% cd BBS/
% curl -L http://cpanmin.us | perl - --installdeps .

Setup database

Put the following in sql/sqlite.sql:

CREATE TABLE IF NOT EXISTS member (
    id           INTEGER NOT NULL PRIMARY KEY,
    name         VARCHAR(255)
);

CREATE TABLE IF NOT EXISTS sessions (
    id           CHAR(72) PRIMARY KEY,
    session_data TEXT
);

CREATE TABLE IF NOT EXISTS entry (
    entry_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    body varchar(255) not null
);

And apply the schema:

% sqlite3 db/development.db < sql/sqlite.sql

You can find the configuration of RDBMS in config/development.pl

use File::Spec;
use File::Basename qw(dirname);
my $basedir = File::Spec->rel2abs(File::Spec->catdir(dirname(__FILE__), '..'));
my $dbpath = File::Spec->catfile($basedir, 'db', 'development.db');
+{
    'DBI' => [
        "dbi:SQLite:dbname=$dbpath", '', '',
        +{
            sqlite_unicode => 1,
        }
    ],
};

Run the web server

You can run the testing web server with the following command:

% perl -Ilib script/bbs-server
BBS: http://127.0.0.1:5000/

, where 5000 is the default port. Then, you can access http://0:5000/ for testing and debugging.

Put Teng schema

Open and edit lib/BBS/DB/Schema.pm as follows:

package BBS::DB::Schema;
use strict;
use warnings;
use utf8;

use Teng::Schema::Declare;

base_row_class 'BBS::DB::Row';

table {
    name 'sessions';
    pk 'id';
    columns qw(session_data);
};

table {
    name 'entry';
    pk 'entry_id';
    columns qw(entry_id body);
};

1;

Implement controller

Open and edit lib/BBS/Web/Dispatcher.pm as follows:

package BBS::Web::Dispatcher;
use strict;
use warnings;

use Amon2::Web::Dispatcher::Lite;

any '/' => sub {
    my ($c) = @_;

    my @entries = $c->db->search(
        entry => {
        }, {
            order_by => 'entry_id DESC',
            limit    => 10,
        }
    );
    return $c->render( "index.tx" => { entries => \@entries, } );
};

post '/post' => sub {
    my ($c) = @_;

    if (my $body = $c->req->param('body')) {
        $c->db->insert(
            entry => +{
                body => $body,
            }
        );
    }
    return $c->redirect('/');
};

1;

Edit template

Open and edit tmpl/index.tx as follows:

: cascade "include/layout.tx"

: override content -> {

<form method="post" action="<: uri_for('/post') :>">
    <input type="text" name="body" />
    <input type="submit" value="Send" />
</form>

<ul>
    <: for $entries -> $entry { :>
    <li><: $entry.entry_id :>. <: $entry.body :></li>
    <: } :>
</ul>

: }

That’s all.

Yes, Amon2 is pretty easy!