Caching methods in php

Quick Tip: How to Cache Data in PHP

It’s crucial to focus on performance when developing PHP apps. Web apps can have thousands or even millions of users, which can lead to slow performance and availability issues. Caching is invaluable in this respect, as it can help avoid performance pitfalls.

What is Caching?

Caching is a way to store frequently accessed data in a temporary storage location to reduce the number of times the data needs to be retrieved from its original storage location. This can greatly improve the performance of a website or application, as accessing data from cache is generally much faster than accessing it from its source.

PHP provides several ways to implement caching. Let’s have a look at each of them.

Output Buffering

Output buffering is a technique in PHP that allows us to store the output of a PHP script in a buffer, rather than sending it directly to the browser. This allows us to modify the output or perform other actions on it before it’s displayed to the user.

To start an output buffer, we can use the ob_start() function. This function will turn output buffering on and begin capturing all output sent by the script. The output can then be stored in a variable using the ob_get_contents() function. Finally, the output buffer can be ended and the output can be sent to the browser using the ob_end_flush() function, or it can be discarded using the ob_end_clean() function.

Here’s an example of how output buffering works:

 ob_start(); // Start the output buffer echo 'This output will be stored in the buffer'; $output = ob_get_contents(); // Get the contents of the output buffer ob_end_clean(); // End the output buffer and discard the contents echo 'This output will be sent to the browser'; 

In this particular example, the string ‘This output will be sent to the browser’ will be echoed only once, since we’re discarding the contents of the output buffer that contains the first echo instruction.

Output buffering can be used as cache, as it allows us to store the output of a PHP script in memory, rather than generating it every time the script is accessed.

Caching Functions

PHP provides several functions specifically for caching data, including apc_store() , memcache_set() , and xcache_set() . These functions can be used to store data in memory, which can be accessed much faster than data stored on a hard drive.

apc_store()

The apc_store() function is part of the Alternative PHP Cache (APC) extension, which provides an opcode cache for PHP. (Opcode cache is a performance optimization technique for PHP that caches the compiled bytecode of PHP scripts in memory, rather than re-parsing and re-compiling the source code on each request.) It stores a value in the APC cache with a specified key and expiration time.

Here’s an example of how to use the apc_store() function to cache a value in memory:

 $value = 'This is the value to cache'; // Store the value in cache for one hour apc_store('cache_key', $value, 3600); 

To retrieve the cached value, we can use the apc_fetch() function:

 $cachedValue = apc_fetch('cache_key'); if ($cachedValue)  // Use the cached value echo $cachedValue; > else  // Generate the value and store it in cache $value = 'This is the value to cache'; apc_store('cache_key', $value, 3600); echo $value; > 

More information on apc_store() can be found here.

memcache_set()

The memcache_set() function is part of the Memcache extension, which allows you to use a Memcache server as a cache for PHP. It stores a value in the Memcache server with a specified key and expiration time.

More information on memcache_set() can be found here.

xcache_set()

The xcache_set() function is part of the XCache extension, which provides a PHP opcode cache and data cache. It stores a value in the XCache cache with a specified key and expiration time.

More information on xcache_set() can be found here.

Caching with a Database

Another option for caching in PHP is to use a database to store cached data. This may seem counterintuitive, as the primary goal of caching is to reduce the number of database accesses and improve performance. However, there are some cases where caching data in a database might be useful.

One such case is if you need to cache large amounts of data that might not fit in memory. Additionally, caching data in a database can be useful if you need to access the cached data from multiple servers, as it allows for easy sharing of cached data between servers.

To cache data in a database, you can use a table with at least two columns: one for the cache key, and one for the cached data. You can then use a SELECT query to check if the cache key exists in the table, and an INSERT or UPDATE query to store the data in the table.

Here’s an example of how to cache data in a MySQL database:

 $db = new mysqli('localhost', 'username', 'password', 'database'); $cacheKey = 'cache_key'; $cachedValue = 'This is the value to cache'; // Check if the cache key exists in the table $result = $db->query("SELECT * FROM cache WHERE cache_key = '$cacheKey'"); if ($result->num_rows > 0)  // Update the cached value $db->query("UPDATE cache SET value = '$cachedValue' WHERE cache_key = '$cacheKey'"); > else  // Insert a new cache row $db->query("INSERT INTO cache (cache_key, value) VALUES ('$cacheKey', '$cachedValue')"); > // Retrieve the cached value $result = $db->query("SELECT * FROM cache WHERE cache_key = '$cacheKey'"); $row = $result->fetch_assoc(); $cachedValue = $row['value']; echo $cachedValue; 

This example demonstrates how to check if a cache key exists in the cache table, and if it does, how to update the cached value. If the cache key doesn’t exist, a new row is inserted into the table with the cache key and value. The cached value is then retrieved from the table and displayed to the user.

Conclusion

Caching is a very powerful technique for improving the performance of a PHP website or application. PHP provides several options for implementing caching, including output buffering, caching functions, and caching with a database. By storing frequently accessed data in a temporary location, we can reduce the number of times the data needs to be retrieved from its source and improve the overall speed and performance of a site.

Share This Article

Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He’s the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.

Источник

Методы кэширования данных на PHP

Методы кэширования данных на PHP

Кэширования промежуточных данных является наиболее примитивным и в то же время самым полезным способом оптимизации, где вам не нужно возиться с какими-либо сложными алгоритмами или предварительной оптимизацией. Если вы собираетесь работать с PHP, то должны быть в курсе о проверенных методах и необходимых для этого инструментах, чтобы ваш сайт летал.

Статические локальные переменные
Быстрым и эффективным способом кэширования результатов функции/метода является использование статических локальных переменных. Рассмотрим пример, который выполняет сложные вычисления:

Теперь при каждом использовании функции в коде, независимо от количества вызовов, функция будет выполнять вычисления только один раз.

Эта методика кэширования не зависит от внешних расширений и поддерживается на уровне языка. Поскольку статические локальные переменные доступны только в пределах функции, в которой они определены, обновление кэша может быть проблематичным. Как правило, для этого необходимо передать какую-либо логическую переменную $use_cache или использовать вместо них статические переменные класса.

Статические переменные не разделяются между процессами PHP и могут кэшировать только на короткое время – охватывающее время выполнения сценария. Хорошим кандидатом является метод, который много раз вызывается из нескольких мест, например, для хранения состояния пользователя или результата, требующего большого объёма математических расчетов.

Такая же функциональность может быть реализована с использованием глобальных переменных, но это приведет к загрязнению глобального пространства имен, поэтому так делать не рекомендуется.

Функции разделяемой памяти APC
PHP является полу-компилируемым языком, а это значит, что каждый сценарий компилируется непосредственно не в машинный код, а в промежуточный код, известный как набор опкодов(байт-код). Данный шаг компиляции потребляет много ресурсов процессора и должен выполняться каждый раз при выполнении сценария. APC (Alternative PHP Cache) это расширение, которое пропускает этот шаг компиляции за счет кэширования опкодов в памяти.

Хотя основным назначением APC обычно считается функциональность кэширования опкодов, расширение также включает некоторые дополнительные функции доступа к памяти.

Теперь преимущество такого подхода очевидно — это использование разделяемой памяти. Этот тип памяти является общим для различных процессов/потоков и, в отличие от статических переменных, данные, которые кэшируются таким способом, будут существовать между несколькими запросами.

Чтобы сделать кэш недействительным, можно использовать значения продолжительности существования (TTL), как в примере выше, или следующие функции:

Другие примечания по поддержке разделяемой памяти в APC:
• В конфигурационном INI файле есть директива для ограничения размера кэша. С соответствующими значениями TTL это дает возможность задавать приоритет кэшированным данным, когда в случае достижения предела памяти истекшие/старые значения будут исключены из кэша.
• С точки зрения производительности — статические переменные всегда будет быстрее, чем функции apc_fetch/apc_store , поскольку доступ к разделяемой памяти должен быть заблокирован и синхронизирован, чтобы предотвратить конфликтные ситуации.
• APC является довольно популярным расширением, и поддерживается основными разработчиками PHP и (весьма вероятно) будет поставляться в комплекте с PHP 5.4.
Memcached для больших распределенных кэшей
Как только сайт начинает получать много посещений, в конечном счете, появляется задача распределения нагрузки между различными машинами. В результате этого обычно требуется переместить PHP на несколько серверов приложений. Если вы использовали APC кэширование раньше — каждый сервер приложений теперь имеет отдельный и дублирующий кэш.

Memcached с другой стороны, представляет собой распределенную службу для хранения данных ключ-значение. Расширение может быть развернуто на отдельном выделенном сервере или в том же стеке PHP приложений. Важно понимать, что нет никакой синхронизации/репликации между несколькими Memcached серверами, и они совсем ничего не знают друг о друге. Фактический сервер, который будет использоваться для хранения, выбирается на стороне клиента с помощью алгоритма хеширования на основе предоставленных данных «ключа». Именно поэтому, в отличие от APC, кэшированные данные не дублируются между различными машинами, а память лучше используется для крупных распределенных приложений.

API очень похож на функциональность разделяемой памяти в APC. Тот же пример с обменом валют, реализованный с помощью PHP расширения Memcache:

Источник

Читайте также:  Html select options html теги
Оцените статью