如何将参数从 plack 应用程序传递到在 builder 中启用的 mojolicious 应用程序? [英] how to pass arguments from an plack app to an mojolicious app enabled in builder?

查看:45
本文介绍了如何将参数从 plack 应用程序传递到在 builder 中启用的 mojolicious 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于示例 plack 应用程序使用大量中间件组件和一个 mojolicious 应用程序在构建器中启用(见下文),我如何将参数从 app.psgi 传递给 Mojolicious不使用丑陋的 %ENV hack 显示?原因传递配置只是一个例子,这可以是任何标量/对象.

given the example plack app using lots of middleware components and an mojolicious app enabled in builder (see below), how can i pass parameters from the app.psgi to Mojolicious without using the ugly %ENV hack shown? of cause passing an config is just an example, this could be any scalar/object.

app.psgi

use Plack::Builder;

$ENV{CONFIG} = {...};

builder {
    ...
    Mojolicious::Commands->start_app('MyApp');
};

MyApp.pm

package MyApp;

use Mojo::Base 'Mojolicious';

sub startup {

    my $self = shift;
    my $r = $self->routes;

    $self->config( $ENV{CONFIG} );

    $r->route('/')->to('home#');        
}

推荐答案

这是一个有趣的问题,通过查看源代码最容易解决.在您的示例中,您正确使用

This is an interesting question and is most easily tackled by looking at the source. In your example you rightly use

Mojolicious::Commands->start_app('MyApp');

查看来源表明start_app 是一个相当简单的包装器:

Looking at the source shows that start_app is a rather simple wrapper:

sub start_app {
  my $self = shift;
  return Mojo::Server->new->build_app(shift)->start(@_);
}

事实证明 build_app以及:

sub build_app {
  my ($self, $app) = @_;
  local $ENV{MOJO_EXE};
  return $app->new unless my $e = Mojo::Loader->new->load($app);
  die ref $e ? $e : qq{Couldn't find application class "$app".\n};
}

返回应用类的新实例.Mojolicious 类的 new 函数更多参与,但最后,它只是调用熟悉的startup 方法并返回实例.

returning a new instance of your app's class. The Mojolicious class's new function is more involved, but in the end, it just calls the familiar startup method and returns the instance.

这意味着您无法轻松地将参数从以标准方式使用的中间件包装器传递给 startup 方法.我可以想到两种机制来完成您想要做的事情:1)编写自己的 build_app 函数来替换服务器的方法,但它将参数传递给 $app->new(依次传递给 startup)或 2) 编写您自己的 start_app 函数,该函数可以调用另一个类似 startup 的函数.

This means that you cannot easily pass arguments to the startup method from your middleware wrapper, used in the standard way. I can think of two mechanisms to accomplish what you want to do: 1) write your own build_app function to replace the server's method but which passes arguments to $app->new (which would get passed to startup in turn) or 2) write your own start_app function which could call another startup-like function.

# in MyApp.pm

sub startup {
  ... # as before
}

sub after_startup {
  ... # your new code here,
      # or even most of what was in `startup` before
}

# app.psgi

builder {
  ...
  my $app = Mojo::Server->new->build_app(shift);
  $app->after_startup(@your_args_here);
  $app->start(@_);
}

这篇关于如何将参数从 plack 应用程序传递到在 builder 中启用的 mojolicious 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆