The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

use $app-object in funtion

Froggie's Avatar

Froggie

24 Jun, 2015 10:22 AM

Hi!
I'm trying to refactor my code from this:
$app->get('/scorecards', 'Froggie\Discgolf\authenticate', function () use ($app) {
$response = array();
    $db = $app->container->get('dbHandler');
    // fetching all scorecards
    $result = $db->getAllScoreCards();

    $response["error"] = false;
    $response["scorecards"] = array();

    // looping through result and preparing scorecard array
    while ($scorecard = $result->fetch_assoc()) {
        $tmp = array();
        $tmp['id'] = $scorecard['id'];
        ...
        array_push($response["scorecards"], $tmp);
    }

    echoResponse(200, $response);
});

to this:

$app->get('/scorecards', 'Froggie\Discgolf\authenticate', 'getScoreCards');

function getScoreCards() {
    $response = array();
    $db = $app->container->get('dbHandler');
    // fetching all scorecards
    $result = $db->getAllScoreCards();
    $response["error"] = false;
    $response["scorecards"] = array();

    // looping through result and preparing scorecard array
    while ($scorecard = $result->fetch_assoc()) {
        $tmp = array();
        $tmp['id'] = $scorecard['id'];
        ...
        array_push($response["scorecards"], $tmp);
    }

    echoResponse(200, $response);
}

But how can I use the $app-object in my function?

  1. 1 Posted by alex on 25 Jun, 2015 09:56 PM

    alex's Avatar

    The simplest way would be to simply fetch it using getInstance:

    $app = \Slim\Slim::getInstance();
    
  2. 2 Posted by Froggie on 01 Jul, 2015 10:08 AM

    Froggie's Avatar

    This solved my problem. Up to next one...

    Thank you!

  3. 3 Posted by Kapoler on 03 Jul, 2015 08:28 AM

    Kapoler's Avatar

    Thank you alex, you're a life-saver :-)

Reply to this discussion

Internal reply

Formatting help / Preview (switch to plain text) No formatting (switch to Markdown)

Attaching KB article:

»

Attached Files

You can attach files up to 10MB

If you don't have an account yet, we need to confirm you're human and not a machine trying to post spam.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac