为返回值调用另一个路由


calling another route for the return value

你好,我是新来的silex,我想做的基本上是

我有一个控制器,使用curl从另一个服务器获取一些东西。然后我有一个不同的路由,我想从返回的值(JSON)显示一些特定的东西。

我想用一些像

$app->get('books', function() use ($app) {
    $content = $app->get('overview/books/');
   $content = json_decode($content);
   return ... ;
})
$app->get('overview/books', function() use ($app) {
    // do the curl operation and return
})

,但显然没有返回我想要的…我怎么解决这个问题?

你应该把json-get代码放在一个服务中,并在两个控制器中使用它。

首先,您应该创建一个包含所有相关代码的类:

class JsonFetcher
{
    public function fetch()
    { /* your code here */ }
}

然后将其注册为服务:

$app["json-fetcher"] = $app->share(function () {
    return new JsonFetcher();
});

然后在你的控制器中使用它:

$app->get("books", function () use ($app) {
    $fetcher = $app["json-fetcher"];
    $json = $fetcher->fetch();
    // your code here
});
编辑:

如果你的服务是一个只有一个方法的类,并且它没有依赖关系,你可以简单地像这样注册一个函数作为服务:

$app["json-fetcher"] = $app->share($app->protect(function () {
    //fetch and return json
}));

您可以在丘疹文档中阅读shareprotect