Question

I have Mojolicious application that uses DBIx::Class. It is working fine, but now I would like to use Mojolicious app object inside DBIx::Class schema module.

In template I use this code to display link:

<a href="<%= $self->url_for('playlist', name => $playlist->name) %>">...</a>

Now I would like to move part of the code that generates url into DBIx::Class schema module, so that in template I could have this:

<a href="<%= $playlist->url %>">...</a>

I tried to achieve this by creating sub url in my Schema::Result::Playlist.pm

sub url {
    my $self = shift;
    my ($app) = @_;
    return $app->url_for('playlist', name => $self->name);
}

This works, but requires passing Mojolicious app to url (ex. <%= $playlist->url($self) %>) which is not nice.

Is there an elegant way to provide Mojolicious app object to all DBIx::Class schema modules at once, maybe during app startup?

This is my schema initialization in my app startup routine:

my $schema = MyApp::Schema->connect(
    'dbi:mysql:dbname=myapp',
    'xxxx',
    'xxxx',
    { mysql_enable_utf8 => 1, },
);
$self->helper( schema => sub { $schema } );
Was it helpful?

Solution

The model in an MVC application should be decoupled so it can be used outside of the app too.

The controllers have the task to fetch data from the model(s) and pass it on to the view(s).

Your templates are perfectly fine, no need to change anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top