Zach Larsen
Zach Larsen

Reputation: 23

How to replace Slim::getInstance() in Slim 3

I am currently trying to follow a Slim tutorial that is utilizing $app = Slim::getInstance(); I don't know much about Slim, so the solutions to use a container do not make sense to me. What can I do to make my function provided below actually run?

function jsonResponse($data, $code = 200)
{
    $app = Slim::getInstance();
    $app->response->setStatus($code);
    $app->response->headers->set(
    'Content-type',
    'application/json; charset=utf-8'
);
return $app->response->setBody(json_encode($data));
}

I am calling this inside another function for logging in that looks like this:

function login($request) {
$user = json_decode($request->getBody());
$username = $user->username;
$password = $user->password;
if (empty($username) || empty($password)) {
    $error = 'Username and password are required';

    // Bad request
    return jsonResponse($error, 400);
}
$sql = "SELECT first_name, username FROM users "
    . "WHERE username = '$username' AND password = '$password'";
$db = getConnection();
$row = array();
try {
    $result = $db->query($sql); 
    if (!$result) {
        $error = 'Invalid query: ' . mysql_error();

        // Internal server error
        return jsonResponse($error, 500);
    }
    $user = $result->fetchAll(PDO::FETCH_OBJ);
    if (empty($user)) {

        // Unauthorized
        return jsonResponse($error, 401);
    }
    $row["user"] = $user;
    $db = null;
} catch(PDOException $e) {
    error_log('{"error":{"text":'. $e->getMessage() .'}}');
    // $error = array( 'error' => array ( 'text' => $e->getMessage() ) );

    // Internal server error
    return jsonResponse($error, 500);
}

// OK, default is 200
return jsonResponse($row);
}

My route for the login function is $app->post('/login_user', 'login');

tl;dr I would like an explanation on how to convert older Slim code that uses getInstance().

Thank you!

Upvotes: 2

Views: 1995

Answers (1)

Jiri
Jiri

Reputation: 435

It's actually pretty straightforward. In this particular case you don't need jsonResponse() function at all. Your login controller will need these changes:

function login($request, $response, $args) {
    // ... some code ...
    if ($isError) {
        return $response->withStatus(500)->withJson($error);
    }
    return $response->withJson($row); // Status=200 is default.
}

In general, as was said in the comments, Slim3 has no static method to get a Singleton instance. If you wanted to hook on the response object in Slim3, the best way would be to create a middleware.

Or, if you really wanted to access $response from external function, you pass it as a function parameter (respecting dependency injection pattern and keeping code testable): jsonResponse($response, $error, 500);.

Technically, $app is a global variable, but I would suggest against accessing it through $GLOBALS.

Upvotes: 1

Related Questions