原文链接:http://www.if-not-true-then-false.com/2012/php-apc-configuration-and-usage-tips-and-tricks/3/
This PHP APC guide is divided on four different section:
3. Howto Use PHP APC User Cache3. Howto Use PHP APC User Cache Examples
3.1 PHP APC User Cache Example with Numeric Values
Here is an example howto use apc_add, apc_cas, apc_fetch, apc_dec and apc_inc:
"; // Update old value with a new value apc_cas('num', 1, 10); // Print just updated value echo "Updated value: ", apc_fetch('num'), ""; // Decrease a stored number echo "Decrease 1: ", apc_dec('num'), ""; echo "Decrease 3: ", apc_dec('num', 3), ""; // Increase a stored number echo "Increase 2: ", apc_inc('num', 2), ""; echo "Increase 1: ", apc_inc('num'), "";?> |
Output:
Initial value: 1Updated value: 10Decrease 1: 9Decrease 3: 6Increase 2: 8Increase 1: 9 |
3.2 PHP APC User Cache Example with String
This example shows howto use apc_fetch, apc_exists, apc_store, apc_clear_cache:
"; // Clear cache apc_clear_cache('user'); // Try to fetch str again echo "str from cache, after user cache is cleared: ", ""; var_dump(apc_fetch('str')); } else { // Save str to cache and set ttl 120 seconds echo 'str not found from cache...saving', ""; $str = "This is just test"; apc_store('str', $str, 120); }?> |
First run output:
str not found from cache...saving |
Second run output:
str from cache: This is just test |
3.3 PHP APC User Cache Example with Array
"; print_r($arr); } else { echo 'arr not found from cache...saving', ""; $arr = array('Test 1', 'Test 2', 'Test 3'); apc_add('arr', $arr, 120); }?> |
First run output:
arr not found from cache...saving |
Second run output:
arr from cache:Array ( [0] => Test 1 [1] => Test 2 [2] => Test 3 ) |
3.3 PHP APC User Cache Example with Object
name = $name; } public function setAge($age) { $this->age = $age; } public function getName() { return $this->name; } public function getAge() { return $this->age; } } // Check if Person object found from cache if ($obj = apc_fetch('person')) { echo "Person data from cache: ", ""; echo "Name: ", $obj->getName(), ""; echo "Age: ", $obj->getAge(), ""; } else { echo 'Person data not found from cache...saving', ""; $obj = new Person; $obj->setName('Test Person'); $obj->setAge(35); apc_add('person', $obj, 3600); }?> |
First run output:
Person data not found from cache...saving |
Second run output:
Person data from cache: Name: Test PersonAge: 35 |
This PHP APC guide is divided on four different section:
3. Howto Use PHP APC User Cache