Skip to content

Using ORLite as model

Stefan Adams edited this page Feb 4, 2014 · 2 revisions

Using ORLite as model for Mojolicious

Working with ORLite as a lightweight object relational mapper is really a joy. Basically what ORLite does for you is to map functions to tables. You can access the tables later by using the object and the function in old style Perl syntax.

Let's have a short application.

#!/usr/bin/env perl
 
package Model;
use strict;
use ORLite {
    file    => 'sample.db',
    unicode => 1,
    create  => sub {
        my $dbh = shift;
        $dbh->do(
            'CREATE TABLE motorcycles (
             id INTEGER PRIMARY KEY,
             type TEXT NOT NULL, 
             brand TEXT NOT NULL,
             color TEXT)'
        );
 
        # just use $dbh->do(...) if you need more
        # tables
        return 1;
      }
};
 
package main;
 
use Mojolicious::Lite;
 
get '/' => sub {
    my $self = shift;
    $self->stash(motorbikes => [Model::Motorcycles->select('order by type')]);
} => 'index';
 
post '/' => sub {
    my $self = shift;
    Model::Motorcycles->create(
        type  => $self->param('type'),
        brand => $self->param('brand'),
        color => $self->param('color')
    );
    $self->redirect_to('/');
};
 
app->start;
 
__DATA__
 
@@ index.html.ep
<!DOCTYPE html>
<html>
  <head><title>Motorcycles</title></head>
  <body>
    <table>
    % foreach my $cycle (@{$motorbikes} ) {
      <tr>
        <td><%= $cycle->type %></td>
        <td><%= $cycle->brand %></td>
        <td><%= $cycle->color %></td>
      </tr>
    % }
    </table>
     
    <p>Enter a new motorcycle here</p>
    <p>
      <%= form_for '/' => (method => 'post') => begin %>
% foreach (qw/type brand color/) {
        <%= uc($_) %>: <%= input_tag $_, 'type' => 'text' %><br />
% }
        <%= submit_button 'Submit motorcycle' %>
      <% end %>
    </p>
  </body>
</html>

This small application allows to enter some data about motorcycles. It uses a simple model class which uses ORLite as lightweight OR mapper. If you look at the generation of the HTML form you'll notice the usage of tag helpers which are part of the Mojolicious installation. They are explained in the documentation in the pages of Mojolicious::Plugin::TagHelpers and Mojolicious::Plugin::DefaultHelpers.

Please note - if you are using Mojolicious::Lite applications there is no need to enable the helpers explictly.

You can find more about ORLite on CPAN ORLite.

Clone this wiki locally