Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a closure for the PDO FETCH instructions

Tags:

closures

php

pdo

It occurs to me that I want to give my PDO result the instructions on how to instantiate itself into an object when it gets iterated later on, but I do not want to perform the logic until that time.

I've been looking for the existence of this PDO functionality but I cannot find it. What I want to do is essentially this:

public function getUsers()
{
    $sql = 'select first_name, last_name, phone, address from users';

    return $this->pdo->query($sql, PDO::FETCH_ASSOC, function($row) {
        $user = new User();
        $user->setName($row['first_name'] . ' ' .$row['last_name'])
             ->setPhoneNumber($row['phone'])
             ->setMailingAddress($row['address']);
        return $user;
    });
}

Is there a good way of accomplishing this with PHP and specifically PDO? Looping through the iterator is not an acceptable answer. I only want to iterate on this recordset once during execution.

like image 411
Jesse Greathouse Avatar asked Dec 30 '25 23:12

Jesse Greathouse


1 Answers

You can use a Generator for this via yield. Only when the internal pointer is on certain iteration, the concrete object will be yielded.

class User {
    public $picture;

    public function __construct($pic) {
        $this->picture = $pic;
    }
}

function getUsers() {
    $pdo = new PDO('mysql:host=localhost;dbname=users', 'root', '');
    $query = "SELECT * FROM votesusers";
    $res = $pdo->query($query);
    while ($row = $res->fetch()) {
        yield new User($row['picture_id']);
    }
}

foreach (getUsers() as $user) {
    var_Dump($user);
}

Output:

object(User)[5]
  public 'picture' => string '2' (length=1)

object(User)[6]
  public 'picture' => string '9' (length=1)

object(User)[5]
  public 'picture' => string '6' (length=1)

object(User)[6]
  public 'picture' => string '1' (length=1)
like image 59
Royal Bg Avatar answered Jan 02 '26 13:01

Royal Bg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!