TL;DR;
How do I make a PDO connection available to the CardOnFile\Controller
class so that it can make database queries? (I think I have to use the container, but not sure how).
Background
I want to avoid having multiple connections to the database each time I instantiate an object that needs database access. So, I think I need to instantiate ONE copy of a database connection (PDO) and then inject it into the classes where it will be needed using League\Route and League\Container.
I don't want to inject the container into the classes, because that's service location. But, I am completely unsure how to get the PDO object into the class that is going to need it so it can do work.
How to I make it so that the mapped callable has database access?
Code:
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=foo;host=localhost';
$user = 'bar';
$password = 'supersecret';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
die(__FILE__ . ":" . __LINE__);
}
$container = new League\Container\Container;
$container->share('response', Zend\Diactoros\Response::class);
$container->share('request', function () {
return Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER, $_GET, $_POST, $_COOKIE, $_FILES
);
});
$container->share('emitter', Zend\Diactoros\Response\SapiEmitter::class);
//DI PDO instance and connection.
$container->share('PDO', $pdo);
$route = new League\Route\RouteCollection($container);
$route->map('GET', '/cards/', 'CardOnFile\Controller::requestEmail' );
$route->map('GET', '/cards/emails/confirm', 'CardOnFile\Controller::getUserController' );
$route->map('GET', '/cards/emails/', 'CardOnFile\Controller::getCardController' );
$response = $route->dispatch($container->get('request'), $container->get('response'));
$container->get('emitter')->emit($response);