mojolicious helper storing an elasticsearch connection mojolicious helper storing an elasticsearch connection elasticsearch elasticsearch

mojolicious helper storing an elasticsearch connection


First of all, has and helper are not the same. has is a lazily built instance attribute. The only argument to an attribute constructor is the instance. For an app, it would look like:

package MyApp;has elasticsearch => sub {  my $app = shift;  Search::ElasticSearch->new($app->config->{es});};sub startup {  my $app = shift;  ...}

This instance is then persistent for the life of the application after first use. I'm not sure if S::ES has any reconnect-on-drop logic, so you might need to think about it a permanent object is really what you want.

In contrast a helper is just a method, available to the app, all controllers and all templates (in the latter case, as a function). The first argument to a helper is a controller instance, whether the current one or a new one, depending on context. Therefore you need to build your helper like:

has (elasticsearch => sub {  my ($c, $config) = @_;  $config ||= $c->app->config->{es};  Search::ElasticSearch->new($config);});

This mechanism will build the instance on demand and can accept pass-in arguments, perhaps for optional configuration override as I have shown in that example.

I hope this answers your questions.