0

I'm upgrading to slim v3. How should I use a database connection? I'm thinking about a service injected with pimple:

DBConnection

final class DBConnection {

    private $db;

    public function __construct() {
        try {
            // Code to open up a DB connection in $db var...
        } catch (Exception $ex) {
            // TODO $app->error ?
        }
    }

    public function getDB() {
        return $this->db;
    }

}

index.php

$container = new \Slim\Container;

$container['db'] = function($container) {
    $connection = new DBConnection();
    return $connection->getDB();
};

What if the db connection raise a PDO (or generic) Exception? In v2 I had something like

$app->error

now what? I've defined a custom errorHandler as well, how can I somehow "redirect" the control over that route?

alexw
  • 8,468
  • 6
  • 54
  • 86
Jumpa
  • 4,319
  • 11
  • 52
  • 100

1 Answers1

0

Slim 3's error handling is very simple as explained in the documentation.

Since you define you container services before instantiating Slim\App, define error handler in the following manner (in index.php):

$container['errorHandler'] = function($container) {
    return function ($request, $response, $exception) use ($container) {
        return $container['response']->withStatus(500)
                                     ->withHeader('Content-Type', 'text/html')
                                     ->write($exception->getMessage());
    };
};

All exception will be caught by the defined handler, as long as:

  • the exception was not caught previously (like in your example code)
  • the exception is not one of these:
    • Slim\Exception\MethodNotAllowedException
    • Slim\Exception\NotFoundException
    • Slim\Exception\SlimException

For the first two you can define your own handlers as well.

So, back to your example:

final class DBConnection {

    private $db;

    public function __construct() {
        // Code to open up a DB connection in $db var...
        // Don't have to catch here
    }

    public function getDB() {
        return $this->db;
    }
}
Georgy Ivanov
  • 1,573
  • 1
  • 17
  • 24