Can someone explain a little bit about caching dynamic PHP pages? - php

I was wondering about caching dynamic PHP pages. Is it really about pre-compiling the PHP code and storing it in byte-code? Something similar to Python's .pyc which is a more compiled and ready to execute version and so that if the system sees that the .pyc file is newer than the .py file, then it won't bother to re-compile to .py file.
So is PHP caching mainly about this? Can someone offer a little bit more information on this?

Depends on the type of caching you are talking about. Opcode caching does exactly like you are saying. It takes the opcode and caches it so that whenever a user visits a particular page, that page does not need to be re-compiled if its opcode is already compiled and in the cache. If you modify a php file the caching mechanism will detect this and re-compile the code and put it in the cache.
If you're talking about caching the data on the page itself this is something different altogether.
Take a look at the Alternative PHP Cache for more info on opcode caching.

What you're describing is a PHP accelerator and they do exactly what you said; store the cached, compiled bytecode so that multiple executions of the same script require only one compilation.
It's also possible to cache the results of executing the PHP script. This usually requires at least a little bit of logic, since the content of the page might have changed since it was cached. For example, you can have a look at the general cache feature provided by CodeIgniter.

Peter D's answer covers opcode caching well. This can save you over 50% of page generation time (subjective) if your pages are simple!
The other caching you want to know about is the caching of data. This could be caching database result sets, a web service response, chunks of HTML or even entire pages!
A simple 'example' should illustrate:
$cache = new Cache();
$dataset;
if (!$dataset == $cache->get('expensiveDataset')){
//run code to fetch dataset from database
$dataset = expensiveOperation();
$cache->set('expensiveDataset', $dataset);
}
echo $dataset; //do something with the data
There are libraries to help with object, function and page level caching. Zend Framework's Zend_Cache component is food for thought and a great implementation if you like what you see.

There are actually a few different forms of caching. What you're referring to is handled by packages such as eAccelerator, MMCache, etc.
While this will help some, where you'll really get a performance boost is in actually caching the HTML output where applicable, or in caching DB result sets for repetitive queries (something like memcache).
Installing any of the opcode cache mechanisms is very easy, but the other two areas of caching I referenced will gain you much larger performance benefits.

Related

PHP ob_start vs opcode APC, explain differences and real world usage?

Premise: I'm not trying to reinvent the wheel, I'm just trying to understand.
Output caching can be implemented easily:
//GetFromMyCache returns the page if it finds the file otherwise returns FALSE
if( ($page = GetFromMyCache($page_id)) !== FALSE )
{
echo $page; //sending out page from cache
exit();
}
//since we reach this point in code, it means page was not in cache
ob_start(); //let's start caching
//we process the page getting data from DB
//saving processed page in cache and flushing it out
echo CachePageAndFlush(ob_get_contents());
explained well in another article, and also in another answer.
But then comes APC (that will be included in PHP6 by default).
Is APC a module that once installed on the server, existing PHP code will run faster without modification?
Is APC automatic?
Then, why are there functions like apc_add?
How do we cache entire pages using APC?
When APC is installed, do I still need to do any caching on my part?
If APC is going to save hosting providers money, why do they not install it? (I mean they should be racing to install it, but I don't see that happening.)
Does installing APC have disadvantages for these hosting providers?
APC is an opcode cache:
The Alternative PHP Cache (APC) is a free and open opcode cache for
PHP. Its goal is to provide a free, open, and robust framework for
caching and optimizing PHP intermediate code.
This is not the same as a template cache (what you are demonstrating), and it has little impact on output buffering. It is not the same thing.
Opcode caching means cache the PHP code after it has been interpreted. This could be any code fragment (not necessarily something that outputs HTML). For example, you could stick classes and the template engine itself in an opcode cache. This would dramatically speed up your code, as the PHP interpreter doesn't need to "interpret" your code again, it can simply load the "interpreted" version from the cache.
Please do not confuse output buffering with a cache. There are many levels of caching, for example, two of the most common that you may be familiar with.
Caching the session
A very basic version of this is a cookie that stores some settings. You only execute the code that "calculates" the settings once (when a user logs in), and for the rest of the session, you use the "cached" settings from the cookie.
Caching the rendered template
This is done when a page that needs to be generated once, but doesn't change very often. For example a "daily specials" page, which is a template. You only generate this once, and then serve the "rendered" page from cache.
None of these use APC
Is APC makes the PHP to run faster on its own?
Yes. In a way. The benefit hugely differs though.
When using APC do I still need to cache rendered HTML?
Bytecode is NOT like resulting HTML. It is the same program as a regular PHP script.
Even with APC enabled, PHP have to process data and render HTML.
I hope you understand the difference now.
APC cache provides both byte-code cache and memory-based storage to store user data.
So, you can also use it to store some user-defined data.
And store whole rendered pages as well (I don't understand your confusion here - what is that 'page' data type you are talking about? Isn't the ob result being just a regular string?).
However, caching of the resulting HTML is not that easy as you imagine.
Premature optimization is the root of all evil.
Start optimizing your site only when you have a reason.
why are Web Hosters waiting to install APC?
There are several reasons. But one is enough - bytecode cache won't make any profit for the usual PHP-based ugly homepage ecommerce site.
APC caches bytecodes. PHP turns source code you write into these when a file gets requested or included, and then gets rid of them. With APC the bytecode stays around.
ob_start turns on an output buffer. It can be used to cache one effect of the program code, which is the text it prints.
Use APC if you want your program to run faster and consume less CPU power. It has no effect on database throughput.
Cache ob_start output if you only want to run the program every now and then and just statically serve its last output. This saves database throughput, at the price of information freshness and personalization.
APC is good when each page request conveys new information, or information specific to the user.
Cache ob_start output if you are running some heavyweight calculations or data access and it's okay that everyone gets the same not-quite-fresh output.

cache methods in php?

what are the available cache methods i could use in php ?
Cache HTML output
Cache some variables
it would be great to implement more than one caching method , so i need them all , all the available out there (i do caching currently with files , any other ideas ?)
Most PHP build don't have a caching mechanism built in. There are extensions though that can take care of caching for you.
Have a look at APC or MemCache
If you are using a framework, then most come with some form of caching mechanism that you can use e.g. Zend Framework's Zend_Cache.
If you are not using a framework then the APC or Memcache as Pelle ten Cate mentioned can be used. The correct approach to use does depend in your situation though, do you have your website or application running on more than server and does the information in the cache need to be shared between those servers? (if yes then something like memcache is your answer, or maybe a database or distributed NoSQL solution if you are feeling brave).
If you code is only running on the one server you could try something simple like serializing your variables, and writing them to disk, then on every request afterwards, see if the files exists, if it does, open it and unserialize the string into the variable you need.
This though is only worth it if it would take a long time to generate the varaible normally,
(e.g longer than it would to open,read,unserialize the file on disk)
For HTML caching you are generally going to get the most mileage from using a proxy like Varnish or Squid to do it for you but i realise that this may not be an option for you.
If its not then you could the write to disk approach i mentioned above, and save chunks of HTML to files. look in the PHP manual for ob_start and its friends.
Since every PHP run starts from scratch on page request, there is nothing that would persist between calls, making cacheing moot.
Well, that's the basic view. Of course there are ways to implement a caching, sort of - and a few packages and extensions do so (like Zend Extensions and APC). However, you should have a very close look whether it actually improves performance. Other methods like memcache (for DB results), or switching from PHP to e.g. Java will often yield better results.
You can store variables in the $_SESSION, but you shouldn't keep larger HTML there.
Please check what you are actually trying to do. "Bytecode cacheing" (that is, saving PHP parsing time) needs to be done by the PHP runtime executable. For cacheing Database (SQL) request/reply-pairs, there is memcache. Cacheing HTML output can be done, but is often not a good idea.
See also an earlier answer on a similar question.

How To cache my index?

How can I cache my PHP index page to the /cache folder so it loads faster? Is this the preferred method to improve load times, or is there a better approach?
You may find interesting the follow links
PHP accelerator
List of PHP accelerators
Fastest method is to cache on the client. After that the different methods will yield variable results depending on the nature of the application and the network. But without any more information its impossible to tell.
You might try:
checking for effective caching of static content
eliminating performance bottlenecks from your code
using a template system
using a caching reverse proxy
caching output using php code
using an opcode cache
What have you tried? What analysis of the system have you done? What are the constraints?
Not a very meaningful question.
C.

PHP APC, educate me

I'm currently implementing memcached into my service but what keeps cropping up is the suggestion that I should also implement APC for caching of the actual code.
I have looked through the few tutorials there are, and the PHP documentation as well, but my main question is, how do I implement it on a large scale? PHP documentation talks about storing variables, but it isn't that detailed.
Forgive me for being uneducated in this area but I would like to know where in real sites this is implemented. Do I literally cache everything or only the parts that are used often, such as functions?
Thanks!
As you know PHP is an interpreted language, so everytime a request arrives to the server it need to open all required and included files, parse them and execute them. What APC offers is to skip the require/include and parsing steps (The files still have to be required, but are stored in memory so access is much much faster), so the scripts just have to be executed. On our website, we use a combination of APC and memcached. APC to speed up the above mentioned steps, and memcached to enable fast and distributed storing and accessing of both global variables (precomputed expensive function calls etc that can be shared by multiple clients for a certain amount of time) as well as session variables. This enables us to have multiple front end servers without losing any client state such as login status etc.
When it comes to what you should cache... well, that really depends on your application. If you have a need for multiple frontends somewhere down the line, I would try to go with memcached for such caching and storing, and use APC as an opcode cache.
APC is both an opcode cache and a general data cache. The latter works pretty much like memcached, whereas the opcode cache works by caching the parsed php-files, so that they won't have to be parsed on each request. That can generally speed up execution time up quite a bit.
You don't have to implement the opcode caching features of APC, you just enable them as a php module.
APC cache size and other configuration information is here.

How do I implement a HTML cache for a PHP site?

What is the best way of implementing a cache for a PHP site? Obviously, there are some things that shouldn't be cached (for example search queries), but I want to find a good solution that will make sure that I avoid the 'digg effect'.
I know there is WP-Cache for WordPress, but I'm writing a custom solution that isn't built on WP. I'm interested in either writing my own cache (if it's simple enough), or you could point me to a nice, light framework. I don't know much Apache though, so if it was a PHP framework then it would be a better fit.
Thanks.
You can use output buffering to selectively save parts of your output (those you want to cache) and display them to the next user if it hasn't been long enough. This way you're still rendering other parts of the page on-the-fly (e.g., customizable boxes, personal information).
If a proxy cache is out of the question, and you're serving complete HTML files, you'll get the best performance by bypassing PHP altogether. Study how WP Super Cache works.
Uncached pages are copied to a cache folder with similar URL structure as your site. On later requests, mod_rewrite notes the existence of the cached file and serves it instead. other RewriteCond directives are used to make sure commenters/logged in users see live PHP requests, but the majority of visitors will be served by Apache directly.
The best way to go is to use a proxy cache (Squid, Varnish) and serve appropriate Cache-Control/Expires headers, along with ETags : see Mark Nottingham's Caching Tutorial for a full description of how caches work and how you can get the most performance out of a caching proxy.
Also check out memcached, and try to cache your database queries (or better yet, pre-rendered page fragments) in there.
I would recommend Memcached or APC. Both are in-memory caching solutions with dead-simple APIs and lots of libraries.
The trouble with those 2 is you need to install them on your web server or another server if it's Memcached.
APC
Pros:
Simple
Fast
Speeds up PHP execution also
Cons
Doesn't work for distributed systems, each machine stores its cache locally
Memcached
Pros:
Fast(ish)
Can be installed on a separate server for all web servers to use
Highly tested, developed at LiveJournal
Used by all the big guys (Facebook, Yahoo, Mozilla)
Cons:
Slower than APC
Possible network latency
Slightly more configuration
I wouldn't recommend writing your own, there are plenty out there. You could go with a disk-based cache if you can't install software on your webserver, but there are possible race issues to deal with. One request could be writing to the file while another is reading.
You actually could cache search queries, even for a few seconds to a minute. Unless your db is being updated more than a few times a second, some delay would be ok.
The PHP Smarty template engine (http://www.smarty.net) includes a fairly advanced caching system.
You can find details in the caching section of the Smarty manual: http://www.smarty.net/manual/en/caching.php
You seems to be looking for a PHP cache framework.
I recommend you the template system TinyButStrong that comes with a very good CacheSystem plugin.
It's simple, light, customizable (you can cache whatever part of the html file you want), very powerful ^^
Simple caching of pages, or parts of pages - the Pear::CacheLite class. I also use APC and memcache for different things, but the other answers I've seen so far are more for more complete, and complex systems. If you just need to save some effort rebuilding a part of a page - Cache_lite with a file-backed store is entirely sufficient, and very simple to implement.
Project Gazelle (an open source torrent site) provides a step by step guide on setting up Memcached on the site which you can easily use on any other website you might want to set up which will handle a lot of traffic.
Grab down the source and read the documentation.

Categories