Search code examples
phpinitializationstartupapc

PHP script to be run at startup (APC variables initialization)


Is it possible to have the PHP server (via php5-fpm) run a PHP script just after it started, and before clients have access to it, in order to perform the initialization of APC variables.

Basically some events are counted during the server life via apc_inc, like

apc_inc('event-xyz-happened');

the event-xyz-happened APC var is permanent (life span is server life, not request life).

The problem is, the event-xyz-happened APC var has to exist before it is incremented (unlike Perl) the first time. apc_inc being pretty fast, I want to avoid solutions like

if ( ! apc_exists('event-xyz-happened')) {
  apc_store('event-xyz-happened', 1);
}
else {
  apc_inc('event-xyz-happened');
}

which not only require a call to apc_exists('event-xyz-happened'), but may also suffer from a race condition when it doesn't exist yet.

--

Is there a solution to create some APC variables before clients have access to the server?


Solution

  • You can use apc_add followed by apc_inc (see http://www.php.net/manual/en/function.apc-add.php)

    // if it doesn't exist, it gets created
    // if it does exist, nothing happens, no race condition
    apc_add('event-xyz-happened', 0); 
    apc_inc('event-xyz-happened', 1);