The method is private, because you won??™t access it from within other classes??”it??™s a helper
class for other methods of Catalog.
The method verifies whether the previous call to it was for the same SELECT query. If it
was, the result cached from the previous call is returned. This small trick improves performance
when the visitor is browsing subpages of the same list of products because the actual
counting in the database is performed only once.
// Create a hash for the sql query
$queryHashCode = md5($countSql . var_export($countSqlParams, true));
// Verify if we have the query results in cache
if (isset ($_SESSION['last_count_hash']) &&
isset ($_SESSION['how_many_pages']) &&
$_SESSION['last_count_hash'] === $queryHashCode)
{
// Retrieve the cached value
$how_many_pages = $_SESSION['how_many_pages'];
}
The number of pages associated with the received query and parameters is saved in the
current visitor??™s session in a variable named how_many_pages. If the conditions aren??™t met, which
means the results of the query aren??™t cached, we calculate them and save them to the session:
else
{
// Execute the query
$items_count = DatabaseHandler::GetOne($countSql, $countSqlParams);
// Calculate the number of pages
$how_many_pages = ceil($items_count / PRODUCTS_PER_PAGE);
// Save the query and its count result in the session
$_SESSION['last_count_hash'] = $queryHashCode;
$_SESSION['how_many_pages'] = $how_many_pages;
}
CHAPTER 5 ?– CREATING THE PRODUCT CATALOG: PART 2 142
In the end, no matter if the number of pages was fetched from the session or calculated
by the database, it is returned to the calling function:
// Return the number of pages
return $how_many_pages;
GetProductsInCategory
GetProductsInCategory() returns the list of products that belong to a particular category.
Pages:
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243