Last active
August 29, 2015 14:26
-
-
Save nyamsprod/d51b66cc005accd9b872 to your computer and use it in GitHub Desktop.
Filtering a Traversable object using PHP SPL filtering capabilities in response to http://www.dragonbe.com/2015/07/speeding-up-database-calls-with-pdo-and.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$pdo = new \PDO( | |
$config['db']['dsn'], | |
$config['db']['username'], | |
$config['db']['password'] | |
); | |
$sql = 'SELECT * FROM `gen_contact` ORDER BY `contact_modified` DESC'; | |
$stmt = $pdo->prepare($sql); | |
$stmt->setFetchMode(\PDO::FETCH_OBJ); | |
$stmt->execute(); | |
$convertToIterator = function (\Traversable $traversable) { | |
foreach ($traversable as $row) { | |
yield $row; | |
} | |
}; | |
$condition = '2015-04-01 00:00:00'; | |
$filterLastPeriod = function ($row) use ($condition) { | |
return (new \DateTime($condition))->format('Y-m-d').' 00:00:00' < $row->contact_modified; | |
}; | |
foreach (new \CallbackFilterIterator($convertToIterator($stmt), $filterLastPeriod) as $row) { | |
var_dump($row); //do something meaningfull with the filtered rows | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment