Search code examples
phpcachingapcob-start

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).

  1. Is APC a module that once installed on the server, existing PHP code will run faster without modification?

    Is APC automatic?

  2. Then, why are there functions like apc_add?

    How do we cache entire pages using APC?

  3. When APC is installed, do I still need to do any caching on my part?

  4. 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?


Solution

  • 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