Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use $app in called function for Slim?

Tags:

json

php

slim

I am trying to make a reusable function, but everytime I try to use $app in the remote function, I get a blank screen. Here is what does work:

$app = new \Slim\Slim();

//GET CHAPTERS
$app->get(
    '/chapters',
    function () use ($app) {
        $app->contentType('application/json');
        executeSql('SELECT * FROM chapters ORDER BY id');
    }
);

//GENERIC SQL EXECUTE
function executeSql($sql) {
    try {
        $db = getConnection();
        $stmt = $db->query($sql);  
        $results = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($results);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

But I am trying to move the json header in the function and can't get this to work (gets the blank white screen):

$app = new \Slim\Slim();

//GET CHAPTERS
$app->get(
    '/chapters',
    function () {
        executeSql('SELECT * FROM chapters ORDER BY id');
    }
);

//GENERIC SQL EXECUTE
function executeSql($sql) use ($app) {
        $app->contentType('application/json');
    try {
        $db = getConnection();
        $stmt = $db->query($sql);  
        $results = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($results);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

Is something wrong with my syntax or how I'm using PHP? I also tried without the "use ($app)" at all but still same problem.

like image 601
TruMan1 Avatar asked Jul 28 '13 14:07

TruMan1


1 Answers

Easy way to fix this is to use getInstance();

function yourFunction(){
   $app = \Slim\Slim::getInstance();
}
like image 193
corysus Avatar answered Oct 05 '22 15:10

corysus