LoginSignup
9

More than 5 years have passed since last update.

Mojoliciousのモデル構成例

Last updated at Posted at 2015-03-06

0. 環境

OS: Ubuntu 12.04 LTS 64
Mojolicious 6.01
plenv: perl 5.18.1

1. ディレクトリ構成

mojo generate app MyAPPによりデフォルト構成は以下の通り。


my_app
├── lib
│   ├── MyApp
│   │   └── Controller
│   │       └── Example.pm
│   └── MyApp.pm
├── log
├── public
│   └── index.html
├── script
│   └── my_app
├── t
│   └── basic.t
└── templates
    ├── example
    │   └── welcome.html.ep
    └── layouts
        └── default.html.ep

2. Modelの追加

 Controllerディレクトリ以下のコントローラから使用する
モデルを追加します。追加するのはModel.pmとModelディレクトリです。

追加後のディレクトリ構成

my_app
├── lib
│   ├── MyApp
│   │   ├── Controller
│   │   │   └── Example.pm
│   │   │   
│   │   ├── Model
│   │   │   └── Hoge.pm
│   │   │
│   │   └── Model.pm
│   └── MyApp.pm
│
├── log
│   └── development.log
├── public
│   └── index.html
├── script
│   └── my_app
├── t
│   └── basic.t
└── templates
    ├── example
    │   └── welcome.html.ep
    └── layouts
        └── default.html.ep

11 directories, 13 files

MyApp.pmにModelを追加

MyApp.pm
package MyApp;
use Mojo::Base 'Mojolicious';

+use MyApp::Model;
+has 'model' => sub {MyApp::Model->new};

自作モデルHogeを作成

Hoge.pm
package MyApp::Model::Hoge;
use Mojo::Base 'Mojolicious';

sub hello {
  my $self = shift;
  # テストのためコメント
  # print('Hello');
  return;
}

1;

Model.pmにHogeを追加。

Model.pm
package MyApp::Model;
use Mojo::Base 'Mojolicious';

use MyApp::Model::Hoge;
has 'hoge' => sub { MyApp::Model::Hoge->new };

1;

Example.pmから呼び出す
welcomeサブルーチンの中に記述。

Example.pm
+ print $self->app->model->hoge->hello;

テスト

モデルのテスト

use Test::More;
use Test::Mojo;

my $t = Test::Mojo->new('MyApp');
$t->get_ok('/')->status_is(200)->content_like(qr/Mojolicious/i);

# モデルテスト
my $app = $t->app;
is($app->model->hoge->hello, "Hello");
done_testing();

関連

http://qiita.com/uchiko/items/5ce3adc2bd96c45545a0
http://search.cpan.org/~sri/Mojolicious-6.66/lib/Mojo/Base.pm
https://github.com/yuki-kimoto/mojolicious-guides-japanese/wiki/Mojo::Base

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9