How can I use Dancer2::Plugin::Database when my code is split into multiple files?

a 夏天 提交于 2019-12-06 07:22:49

When you call use Dancer2; in MyServices::Submission, you're actually creating a separate Dancer2 app:

As soon as you import Dancer2 (by calling use Dancer2), you create a Dancer2 App. It will use your class name (defined by either the package function in Perl or the default in Perl: main) to define the Dancer2 App name. This is how Dancer2 will recognize your application.

This introduces an interesting situation. If you wish to separate your App to multiple files, you're actually creating multiple applications.

So what?

This means that any engine defined in an application, because the application is a complete separate scope, will not be available to a different application:

package MyApp::User {
      use Dancer2;
      set serializer => 'JSON';
      get '/view' => sub {...};
 }

package MyApp::User::Edit {
     use Dancer2;
     get '/edit' => sub {...};
 }

These are two different Dancer2 Apps. They have different scopes, contexts, and thus different engines. While MyApp::User has a serializer (the JSON one) defined, MyApp::User::Edit will not have that configuration.


You can use the appname option when you import Dancer2 to say that your module should extend an app instead of creating a new one:

package MyServices::Submission;

use Dancer2 appname => 'MyApp';
use Dancer2::Plugin::Database;

sub databaseTest {
    my $dbh = database;                                 
    return 'success';
}

1;

Now the configuration and engines from the main app will be available inside MyServices::Submission. You can even add additional routes here.


As an aside, splitting up your application like this is a great idea; if you're interested in other techniques, someone on the Dancer users mailing list wrote up some pretty thorough recommendations on how to organize medium- to large-scale Dancer applications. The recommendations are split into six parts; see here for the full listing.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!