Reshad
Reshad

Reputation: 2652

calling another route for the return value

hello I am new to silex and what I try to do basically is

I have one controller that uses curl to fetch something from another server. Then I have a different route where I want to show something specific from that value(JSON) returned.

I thought of using something like

$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

})

but obviously that doesn't return what I want.. How can I solve this?

Upvotes: 0

Views: 123

Answers (1)

Maerlyn
Maerlyn

Reputation: 34105

You should put your json-getting code in a service and use that in both controllers.

First, you should create a class that will contain all your relevant code:

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

then register it as a service:

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

Then use it in your controller:

$app->get("books", function () use ($app) {
    $fetcher = $app["json-fetcher"];
    $json = $fetcher->fetch();

    // your code here
});

Edit:

If your service would be a one-method class, and it has no dependencies, you may simply register a function as a service like this:

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

You can read about share and protect in the Pimple docs.

Upvotes: 2

Related Questions