Items can be iterated with the help of arrays in PHP but when arrays are not available, there is alternate and even more efficient method to undertake the same task. This is particularly useful while reading records from a database or lines of text read from a file. In this tutorial, we would create a class that counts the number of users who are logged in to a web application by retrieving records from a database. First, we need to define a class to store ID and email.
1 2 3 4 5 |
Class user { Public $id, $email; } |
For this, we also need a LoggedIn class which would handle a collection of users who have logged in.
1 2 3 4 5 6 7 |
Class LoggedIn { private $rec; private $cursor; private $item; } |
The constructor of this class would call the function FetchLoggedIn() to run the database query:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Public function_construct() { $this->fetchloggedin(); } Private function fetchloggedin() { $this->cursor = -1; $this->item = null; $db = new PDO (‘mysql:host =localhost ; dbname = dhname’, ‘dbuser’, ‘dhpass’) $this->rec = $db->prepare ( ‘SELECT id, email FROM ‘user’ WHERE loggedin = 1;’, Array (PDO :: ATTR_CURSOR => PDO :: CURSOR_FWDONLY) ); $this->rec->setFetchMode (PDO :: FETCH_INTO, new User()); |
In the above piece of code, $this->cursor is the current record number (zero based). It’s initially set to -1 because we haven’t retrieved any records. $this->item will hold the current User object. $this->rec is the set of records (if any) returned from our SQL query. $this->rec->setFetchMode line sets the default PDO fetch mode. When we fetch a row, a new instance of the User class is returned with the $id and $email properties mapped to the record.
Since our class implements Countable, we must create a public method named count () which returns the number items in the collection — in this case, the number of rows returned by our SQL query:
1 2 3 4 5 |
Public function count () { Return $this->rec->rowCount () } |
The following line calls next (), our second Iterator method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Public function next () { $this->cursor++; $this->item = $this->rec->fetch (PDO :: FETCH_ORI_NEXT); } Finally, we require a public valid () method. This is called immediately after the loop executes next (), it must return true if an item is available: Public function valid () { Return ($this->cursor < $this->count()); } |
This code can be used to can count or iterate over logged-in users and is a pretty efficient alternative to arrays.