An introduction to caching with php
by Nick Papanotas
IntroductionIn this article I will try to give a view of what is the custom caching with php, why and how we can use it.In the modern days, most of the sites are database driven. That means that your site is actually an application which retrieves data from a DBMS ( database managment system, eg MySQL) , parses the data and shows the result to the user. Most of these data are usually don't change frequently or don't change at all, and the reason that we use the database is that we can easilly update the site and the content.A problem that this process creates is the server overhead. Every time we execute a query in the database, the instance of our script will call the DBMS, and then the DBMS will send the results of the query. This is time consuming, and especcially for sites with heavy traffic is a real big problem.How we can solve this problem?There are two ways to solve this if you want to make your site faster. First is optimizing the queries, but we will not talk about this at the present article. The second and most valuable is using some kind of custom caching technique.Custom caching with phpFirst let me explain the idea behind custom caching. When we have dynamic pages that their data is not updated frequently, we can use a 'system' that will be able to create the page, and then store it for later use. That means that after the page's creation, our application will not run the queries again in order to display the page, but it will show the cached one. Of course this system must be able to keep the cached pages for a time period that we will set.Let's code itHere is a simple class that will do the job. Let's see the code first :Code:Now let me explain :function cache()This is the constructor function of the class. The job of this function is to check if there is a cached file for the page that we want, or it should create it. Here is how this is done :$this->file = $this->cache_dir . urlencode( $_SERVER['REQUEST_URI'] );This line creates the file name of our cached page. So the cached file will be something like /path/to/cache/dir/request_uriif ( file_exists ( $this->file )
About the Author
Nick Papanotas is a proffesional web developer since 1998 living in Greece. At 2001 he enstablished his own web development firm. Also he owns some webmaster related sites such as the webdigity webmaster forum and the Topsites sublime directory Visit their website at: http://www.thetopsites.net/
Tell others about
this page:
Comments? Questions? Email Here