角色和猴子补丁 Mojo::Message::Response

sim*_*one 5 perl mojolicious

我正在尝试向 Mojo::UserAgent 添加一个角色来处理对 wikidata SPARQL 服务的查询。

特别是,我希望能够修改响应,以便服务提供的 JSON 更可用。

其要点是我希望能够写

my $ua = Mojo::UserAgent->new->with_roles('+Wikidata');

my $tx = $ua->query($some_sparql); # ->query is defined by Mojo::UserAgent::Role::Wikidata

my $items = $tx->res->items; # this is the crux of the question
Run Code Online (Sandbox Code Playgroud)

但这意味着 - 据我所知:

  • 捕获具有 Wikidata 角色的用户代理生成的交易
  • 猴子补丁或向这些事务中的响应添加角色

问题是:

  1. 这是一个坏主意吗?
  2. 如果不是,我该怎么做?

bri*_*foy 3

我只是创建一个包装器:

sub query {
    ... do whatever you need to make the request from the query ...
    my $tx = $ua->get( ... );
    ... do whatever you want to extract results ...
    }
Run Code Online (Sandbox Code Playgroud)

我宁愿将用户代理级别和应用程序级别分开。由于您添加的功能与用户代理无关,因此我认为您不应该将其添加为用户代理对象。