php pdo repository repositories

// index.php require 'vendor/autoload.php'; use Repositories\PostRepository; try { $pdo = new PDO('sqlite:database.sqlite'); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo $e->getMessage(); die(); } $posts = (new PostRepository($pdo))->getPublished(); foreach ($posts as $post) { echo "# $post->title"; }

// Repositories/PostRepository.php

namespace Repositories;

class PostRepository
{
    protected $pdo;

    public function __construct(\PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function getPublished()
    {
        return $this->pdo->query('SELECT * FROM posts WHERE published_at <= CURRENT_DATE')->fetchAll();
    }

    public function findById($id)
    {
        // For simplicity, no worries about SQL injection
        return $this->pdo->query('SELECT * FROM posts WHERE id = ' .  $id)->fetch();
    }
}

interface PostRepository { public function getPublished(); } class DbPostRepository implements PostRepository { public function getPublished() { // from database } } class FsPostRepository implements PostRepository { public function getPublished() { // from file system } }

No hay comentarios:

Publicar un comentario

linux ubuntu mint actualizar chrome

 desde una terminal: $ sudo apt update $ sudo apt install google-chrome-stable