Mad::Ma...Tutorial(3)
β¨ Mad::Mapper::Guides::Tutorial β¨
okay bestie, welcome to the Mad::Mapper::Guides::Tutorial page, straight outta the User Contributed Perl Documentation section π
π NAME π
Mad::Mapper::Guides::Tutorial β the whole entire how-to for using Mad::Mapper in your app π¦
πΈ OVERVIEW πΈ
So likeβ¦ this tutorial is a short lil intro to how you can actually use Mad::Mapper in your application. That's it, that's the overview. Lowkey perfect. π
π§ TUTORIAL π§
π Create a model
The snippet below? Yeah that's literally enough to define a model β¨ A model should contain all the columns that you want to map to your table. And in many cases you don't even need to define a table, because it gets automatically created from the last part of the package name. Slay. π
# name your model
package MyApp::Model::User;
# import all the helpers from Mad::Mapper
use Mad::Mapper -base;
# columns become accessors, just like you would define with "has"
col id => undef;
col email => '';
See also Mad::Mapper::Guides::Custom if you want more control π«Ά (iykyk)
π¦ Application code
The code below shows how you can use the models in a Mojolicious::Lite application. The example connects to postrgres using Mojo::Pg, but you can also use Mojo::SQLite or Mojo::mysql π
use Mojolicious::Lite;
use Mojo::Pg;
# create a database object from either Mojo::Pg,
# Mojo::SQLite or Mojo::mysql
my $pg = Mojo::Pg->new;
# create a helper method which makes it easy to
# access your models
helper model => sub {
my $c = shift;
my $model = "MyApp::Model::" .shift;
Mojo::Loader::load_class($model);
return $model->new(db => $pg->db, @_);
};
# render a user profile page
get "/profile" => sub {
my $c = shift;
my $user = $c->model(User => id => $c->session("uid"));
$c->delay(
sub {
my ($delay) = @_;
$user->load($delay->begin);
},
sub {
my ($delay, $err) = @_;
return $c->render_exception($err) if $err;
return $c->render(user => $user);
},
);
};
# update the MyApp::Model::User model
post "/profile" => sub {
my $c = shift;
my $user = $c->model(User => id => $c->session("uid"));
$c->delay(
sub {
my ($delay) = @_;
$user->email($c->param("email"));
$user->save($delay->begin);
},
sub {
my ($delay, $err) = @_;
return $c->render_exception($err) if $err;
return $c->render(user => $user);
},
);
};
the way this whole flow justβ¦ works?? ππ₯
π COPYRIGHT AND LICENSE π
Copyright (C) 2014-2016, Jan Henning Thorsen
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0 β¨
π AUTHOR π
Jan Henning Thorsen β "jhthorsen@cpan.org" π
and that's a wrap, bestie π this was Mad::Mapper::Guides::Tutorial, perl v5.42.2, dated 2026-06-09, delivered to you by the User Contributed Perl Documentation crew. mwah, go build something iconic πβπ
π¦ where this page comes from
- fedora 44: perl-Mad-Mapper 0.09-2.fc44 Β· Artistic-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms