Page caching in CodeIgniter
0 1733
- Caching is the process of storing copies of data in a temporary storage location so that they can be accessed more quickly.
- Page caching makes the page loading faster and improves the working of the application.
- Although CodeIgniter is already a fast mechanism we can make it faster by enabling page caching.
- Caching can be enabled on a per-page basis. We can also set the expiration time of caching after this time period it will be removed automatically.
- Cache files are stored in the application/cache directory of the project.
Related Topics:
Codeigniter Interview Questions
Cookie management in Codeigniter
Common functions in Codeigniter
Enabling Caching:
Put the given tag in any of your controller files to enable the caching.
$this->output->cache($n);
Where,
$n represents the number of minutes you want the page to remain cached between refreshes.
Disable Caching:
Although the cache file will be removed automatically after the expiration time, we can also delete that file manually by adding the following lines into the controller file.
// Deletes cache for the currently requested URI
$this->output->delete_cache();
// Deletes cache for /foo/bar
$this->output->delete_cache('/foo/bar');
Example:
Step 1 Open the application/controllers directory and create a new controller file Cache_controller.php.
<?php
class Cache_controller extends CI_Controller {
public function index() {
$this->output->cache(1);
$this->load->view('cache_view');
}
public function delete_cache() {
$this->output->delete_cache('Cache_controller');
echo "Deleted successfully";
}
}
?>
Step 2 Open the application/views directory and create a new view file cache_view.php.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Codeigniter Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Page caching example</h2>
</div>
</body>
</html>
Step 3 Now, enter the given URL into the browser and run the Cache_controller to see the result.
http://localhost/ci/index.php/Cache_controller
After execution, this page will also be cached into the application/cache folder.
If you want to delete this cache file, run the given URL into the browser.
http://localhost/ci/index.php/Cache_controller/delete_cache
Share:
Comments
Waiting for your comments