How can the DRY principle be applied to PHP code to avoid repeating database queries?
Repeated database queries can be avoided in PHP code by implementing a caching mechanism. One way to do this is by storing the results of the database query in a cache (such as Redis or Memcached) the first time it is executed, and then retrieving the results from the cache on subsequent calls instead of querying the database again. This follows the DRY (Don't Repeat Yourself) principle by ensuring that the database query is only executed once and the results are reused.
// Check if the data is already in cache
$cacheKey = 'my_unique_cache_key';
$cachedData = $cache->get($cacheKey);
if (!$cachedData) {
// If data is not in cache, query the database
$result = $db->query("SELECT * FROM my_table");
// Store the result in cache
$cache->set($cacheKey, $result);
} else {
// If data is in cache, use the cached data
$result = $cachedData;
}
// Process the query result
foreach ($result as $row) {
// Do something with each row
}