Perex19
Perex19

Reputation: 354

Slim framework, cannot reach pdo sql server connection that is inside a container from a controller

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:

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.

Upvotes: 1

Views: 1416

Answers (2)

ahmet
ahmet

Reputation: 646

You are getting 500 because in your CourseController.php file, PHP tries to find PDO class under App\Controllers namespace.

You have to use a leading backslash to indicate that PDO is a global class:

$results = $statement->fetchAll(\PDO::FETCH_ASSOC);

Upvotes: 2

Rob Allen
Rob Allen

Reputation: 12778

A 500 error means that a PHP error has occurred.

Firstly change your PDO instantiation to enable errors:

$pdo = new PDO(
    "sqlsrv:Server=" . $db['host'] . ";Database=" . $db['dbname'],
    $db['user'],
    $db['pass'],
    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);

To view the errors directly, update your Slim settings to enable error display:

$config = [
    'settings' => [
        'displayErrorDetails' => true,
    ],
];
$app = new Slim\App();

You should now see the error displayed. Alternatively look in the PHP error log and you should see it there.

Upvotes: 0

Related Questions