search
HomeBackend DevelopmentPHP Tutorial[codeigniter 5], query cache

Database Cache Class

The database cache class allows you to save database query results in text files to reduce database access.

Important

When caching is enabled, this class will be automatically loaded by the database driver, do not load it manually.

Important

Not all query results can be cached, please read the content of this page carefully.

Enable caching

Enabling caching requires three steps:

  • Create a writable directory on the server to save cache files;
  • Set its directory path through the cachedir parameter in the file application/config/database.php ;
  • By setting the cache_on parameter in the file application/config/database.php to TRUE, you can also manually configure it using the following method.

Once caching is enabled, every time a page is loaded, as long as the page contains database queries, it will be automatically cached.

How does caching work?

CodeIgniter’s query caching system will automatically run when you visit a page. If caching is enabled, when the page is first loaded, the query result object is serialized and saved to a text file on the server. When you access the page next time, the cache file will be used directly without accessing the database. In this way, your database access will be reduced to 0 for the cached page.

Only read type (SELECT) queries can be cached, because only this type of query will produce results. Write-type queries (INSERT, UPDATE, etc.) do not generate results, so they will not be cached.

Cache files never expire, and all queries will always be available as long as they are cached unless you delete them. You can delete the cache for specific pages, or you can clear the entire cache. Generally speaking, you can use the following function to clear the cache when certain events occur (such as data being added to the database).

Can caching improve site performance?

Whether caching can achieve performance gains depends on many factors. If you have a heavily optimized database under low load, you may not see a performance improvement. And if your database is being accessed heavily, you may see performance improvements after caching, assuming your file system doesn't have too much overhead. One thing to remember is that caching simply changes the way data is obtained, from accessing the database to accessing the file system.

For example, in some cluster server environments, caching is actually harmful due to too frequent file system operations. Caching may only be beneficial in a shared, single-server environment. Unfortunately, there is no single answer to the question of whether you need to cache your database, it all depends on your situation.

How are cache files stored?

CodeIgniter caches each query into its own cache file, which is further organized into respective subdirectories based on the controller method called. To be more precise, subdirectories are named using the first two segments of your URI (controller name and method name).

For example, you have a blog controller and a comments method with three different queries. The caching system will create a directory named blog+comments and generate three cache files in this directory.

If your URI contains dynamic queries (such as when using paging), each query instance will generate its own separate cache file. Therefore, the number of cache files may eventually be several times the number of queries on your page. Case.

Manage your cache files

Since cache files do not expire, then there should be a mechanism to delete the cache in your application, for example, we assume you have a blog and allow users to comment, whenever a new comment is submitted When doing so, you should delete the cache file corresponding to the controller method that displays comments. There are two different methods for deleting cached data.

Not all database methods are compatible with caching

Finally, we must point out that the cached result object is just a simplified version of the result object. Because of this, several methods of querying results cannot be used.

The methods listed below cannot be used on cached result objects:

  • num_fields()
  • field_names()
  • field_data()
  • free_result()

At the same time, both result_id and conn_id id cannot be used either, because these two ids are only suitable for real-time database operations.

Function reference

$this->db->cache_on() / $this->db->cache_off()

is used to manually enable/disable cache when you don’t want to cache something These two methods can be useful when querying. Example:

// Turn caching on
$this->db->cache_on();
$query = $this->db->query("SELECT * FROM mytable");

// Turn caching off for this one query
$this->db->cache_off();
$query = $this->db->query("SELECT * FROM members WHERE member_id = '$current_user'");

// Turn caching back on
$this->db->cache_on();
$query = $this->db->query("SELECT * FROM another_table");

$this->db->cache_delete()

Deletes the cache file for a specific page, which is useful when you need to clear the cache after updating your database.

The cache system writes the cache into the corresponding cache file according to the URI of the page you visit. For example, if you are visiting the page example.com/index.php/blog/comments, the cache system will save the cache file. Go to the blog+comments directory. To delete these cache files, you can use:

$this->db->cache_delete('blog', 'comments');

如果你没提供任何参数,将会清除当前 URI 对应的缓存文件。

$this->db->cache_delete_all()

清除所有的缓存文件,例如:

$this->db->cache_delete_all();

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了[codeigniter 五]、查询缓存,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools