Hi.
I'm taking my first steps with SPL library
so to practice with it I made this snippet:
class DbWrapper{
public $pdo= null;
public function __construct(){
try{
$this->pdo= new PDO(CONN_STRING, DB_USER, DB_PASSWORD);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
throw $e;
}
}
final public function __destruct(){
$this->pdo= null;
}
}
class NewsList implements Iterator{
private $pdo= null;
private $sth = null;
private $row = null;
function __construct($page = 1, $limit = 20){
$this->pdo= new DbWrapper();
$this->sth= $this->pdo->pdo->prepare("SELECT * FROM news ORDER BY news_id LIMIT ". ($page-1) .", $limit");
$this->sth->execute();
}
public function rewind(){
$this->row= $this->sth->fetch(PDO::FETCH_OBJ,0);
return $this->row;
}
public function next(){
$this->row= $this->sth->fetch(PDO::FETCH_OBJ);
return $this->row;
}
public function valid(){
if($this->row === false){
$this->sth= null;
return false;
}
return true;
}
public function current(){
return $this->row;
}
// Not Used.
public function key(){
return true;
}
}
try{
$newsList= new NewsList(1);
foreach($newsList as $row){
print_r($row);
}
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
Is it the right way ?
Thanks in advance .
Bye.
I'm taking my first steps with SPL library
so to practice with it I made this snippet:
class DbWrapper{
public $pdo= null;
public function __construct(){
try{
$this->pdo= new PDO(CONN_STRING, DB_USER, DB_PASSWORD);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
throw $e;
}
}
final public function __destruct(){
$this->pdo= null;
}
}
class NewsList implements Iterator{
private $pdo= null;
private $sth = null;
private $row = null;
function __construct($page = 1, $limit = 20){
$this->pdo= new DbWrapper();
$this->sth= $this->pdo->pdo->prepare("SELECT * FROM news ORDER BY news_id LIMIT ". ($page-1) .", $limit");
$this->sth->execute();
}
public function rewind(){
$this->row= $this->sth->fetch(PDO::FETCH_OBJ,0);
return $this->row;
}
public function next(){
$this->row= $this->sth->fetch(PDO::FETCH_OBJ);
return $this->row;
}
public function valid(){
if($this->row === false){
$this->sth= null;
return false;
}
return true;
}
public function current(){
return $this->row;
}
// Not Used.
public function key(){
return true;
}
}
try{
$newsList= new NewsList(1);
foreach($newsList as $row){
print_r($row);
}
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
Is it the right way ?
Thanks in advance .
Bye.