Skip to content

Instantly share code, notes, and snippets.

@fukata
Created September 23, 2012 14:45
Show Gist options
  • Save fukata/3771718 to your computer and use it in GitHub Desktop.
Save fukata/3771718 to your computer and use it in GitHub Desktop.
My Mojolicious FW
use strict;
use warnings;
use utf8;
package MyApp::Model::Example;
use Mojo::Base 'MyApp::Model';
sub say {
"Hello World from MyApp::Model::Example";
}
1;
use strict;
use warnings;
use utf8;
package MyApp::Model;
use Mojo::Base -base;
my $_app;
has app => sub { $_app };
sub new {
my ( $class, $app ) = @_;
my $self = $class->SUPER::new;
$_app = $app;
$self;
}
1;
use strict;
use warnings;
use utf8;
package MyApp::Mojolicious::Plugin::Model;
use Mojo::Base 'Mojolicious::Plugin';
use UNIVERSAL::require;
use Carp;
sub register {
my $self = shift;
my $app = shift;
my $conf = shift || {};
$conf->{namespace} ||= 'MyApp::Model';
my $cache = {};
my $getter = sub {
return sub {
my ( $name, $opt ) = @_;
$opt->{cache} ||= 1;
my $model = $cache->{$name} unless $opt->{cache};
my $module = "$conf->{namespace}::$name";
unless ($model) {
$module->use or croak $@;
$cache->{$module} = $module->new($app);
}
return $cache->{$module};
};
};
$app->attr( 'model' => $getter );
$getter;
}
1;
package MyApp::Web::Controller::Root;
use Mojo::Base 'Mojolicious::Controller';
# This action will render a template
sub index {
my $self = shift;
# Render template "root/index.html.ep" with message
my $logic = $self->app->logic->('Example');
$self->render( message => $logic->say );
}
1;
sub setup {
...
# Add custom plugin
push @{ $self->plugins->namespaces }, 'MyApp::Mojolicious::Plugin';
# Load Model Plugin
$self->plugin( Model => {} );
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment