@HieuTruong You would want to create a container for your database connection and pass that object in as the function parameter rather than app:
$c = $app->getContainer();
$c['db'] = function() {
return new DB($host,$user,$pass,$name);
};
$app->post('/search/[{phone}]', function($request, $response, $args) use ($c) {
$token = $request->getParam('token');
$phone = $args['phone'];
if (isTokenValid($c->db, $token)){
return $response->withJson("valid");
}
return $response->withJson("invalid");
});
function isTokenValid($db, $token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $db->prepare($sql);
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
Containers help make your own code reusable, testable and independent from the Slim app object.
Also, rather than $this->response, you can just use $response.