In my app.php I set up a container where I configure the database connection:
$container['db'] = function ($c) {
$db = $c['settings']['db'];
$pdo = new PDO("sqlsrv:Server=" . $db['host'] . ";Database=" . $db['dbname'], $db['user'], $db['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
return $pdo;
};
and specify route and controller related information:
$container['CourseController'] = function($container)
{
return new \App\Controllers\CourseController($container);
};
require __DIR__ . '/../app/routes.php';
In my routes.php, I have a single route:
<?php
$app->get('/courses', 'CourseController:getAll');
and below are my Controller.php and CourseController.php classes:
<?php
namespace App\Controllers;
class Controller
{
protected $container;
public function __construct($container)
{
$this->container = $container;
}
}
<?php
namespace App\Controllers;
class CourseController extends Controller
{
public function getAll($request, $response)
{
try
{
$statement = $this->container->db->prepare("SELECT * FROM Course");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$response->getBody()->write(json_encode($results));
return $response;
}
catch(PDOException $e)
{
print $e->getMessage();
}
}
}
I am getting 500 error and unable to track down the problem. Here is what I know so far:
- I don't have any problems connecting to my database; if I put my routing code inside app.php i am able to retrieve the results of my query.
- I am passing the container to my controller. By using var_dump($this->container) on my controller I observe that container is fine.
- var_dump($this->container->db) is empty though. So, I am assuming that the pdo object wasn't passed or the connection was lost.
- I have tried this suggestion to no avail: "The sqlsrv extension will fail to connect when using error mode PDO::ERRMODE_EXCEPTION (default). To connect, you will need to explicitly pass array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING) (or PDO::ERRMODE_SILENT) into the constructor, or override the getDefaultOptions() method when using sqlsrv." from https://github.com/FaaPz/Slim-PDO
Is there a way for me to pass my pdo connection properly to my controllers by using a container and not get a 500? I am open to other solutions as well if this is not possible.