Home » Php » php – How do I use PDO::FETCH_CLASS with namespace?

php – How do I use PDO::FETCH_CLASS with namespace?

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m learning PHP and right now I’m displaying some articles with PDO. I have some issue using PDO::FETCH_CLASS with the usage of namespace.

my folder architecture:

class/
- Post.php
layout/
-articles/
--articles.php
public/
-index.php (contains my router)

Post.php

namespace App\Articles;

class Post {
    private $id;
    private $name;
    private $content;
    private $date;

    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getContent()
    {
        return $this->content;
    }
    public function getExcerpt()
    {
        $res = $this->content;
        return (strlen($res) > 150) ? substr($res, 0, 150) . '...' : $res;
    }
    public function getDate()
    {
        return $this->date = date('d-m-Y', $this->date);
    }
}

data.db contains only four columns: id, name(text), content(text), created_at(int)

The part I have trouble with:

use App\Articles\Post;

$pdo = new PDO('sqlite:../data.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
try {
    $query = $pdo->query('SELECT * FROM posts');
    $posts = $query->fetchAll(PDO::FETCH_CLASS, 'Post');
} catch (PDOException $e) {
    $error = $e->getMessage();
}

I tried different typing instead of 'Postlike

'App\Articles\'
'App\Articles\Post'
'App\Articles\::POST'
...

I can’t manage to make it works with namepsace.
It works with a require '../class/Post.php'.

Is there a solution for this problem or should I just use the require ?

How to&Answers:

PDO does not look up aliased class names or resolve the current namespace. So you have to pass it explicitely:

$query = $pdo->prepare('SELECT * FROM posts');
$query->execute();
$posts = $query->fetchAll(PDO::FETCH_CLASS, __NAMESPACE__ . '\post');

Using query instead of prepare will cause pdo error, I changed to prepare.

And you can’t use NAMESPACE if its separate from the class, but you can use full path 'app\controller\post'.

See this answer and question https://stackoverflow.com/a/20176944/12232340

Answer:

I forgot to add the folder Articles in class/ so App\Articles\Post couldn’t be find.

Answer:

hi try to read somting about autoloading classes https://www.php.net/manual/en/language.oop5.autoload.php

if you dont have autoloading in code, simply using

use App\Articles\Post;

does nothing,or as you stated self using require is right solution