Skip to content
Alexandre Debusschère edited this page Aug 17, 2020 · 1 revision

If you need a simple connection to a database, you can implement a quick solution using PDO then pass it to your controllers.

Adding a PDO instance in the container

In your config/container.php file, add a new PDO::class entry and configure it.
Example:

/*
 * PDO
 * ---
 *
 * Create the PDO instance here to pass it around in the different handlers and/or middlewares.
 */
$container->set(PDO::class, function() {
    return new PDO('mysql:host=localhost;dbname=borsch', 'root', 'root', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_general_ci'
    ]);
})->cache(true);

Passing the PDO instance to a middleware or request handler

Simply require the PDO instance in your handler constructor, the container will take care of instantiating it with the PDO instance.

namespace App\Handler;

use Laminas\Diactoros\Response\JsonResponse;
use PDO;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class OrderHandler implements RequestHandlerInterface
{

    /** @var PDO */
    protected $pdo;

    /**
     * OrderHandler constructor.
     *
     * @param PDO $pdo
     */
    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    /**
     * Really basic example, shouldn't be used like this in production...
     *
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $statement = $this->pdo->prepare('SELECT * from `orders`');
        $statement->execute();

        return new JsonResponse($statement->fetchAll());
    }
}