## 使用?[APC](http://php.net/manual/zh/book.apc.php)
在一個標準的 PHP 環境中,每次訪問PHP腳本時,腳本都會被編譯然后執行。 一次又一次地花費時間編譯相同的腳本對于大型站點會造成性能問題。
解決方案是采用一個 opcode 緩存。 opcode 緩存是一個能夠記下每個腳本經過編譯的版本,這樣服務器就不需要浪費時間一次又一次地編譯了。 通常這些 opcode 緩存系統也能智能地檢測到一個腳本是否發生改變,因此當你升級 PHP 源碼時,并不需要手動清空緩存。
PHP 5.5 內建了一個緩存?[OPcache](http://php.net/manual/en/book.opcache.php)。PHP 5.2 - 5.4 下可以作為PECL擴展安裝。
此外還有幾個PHP opcode 緩存值得關注?[eaccelerator](http://sourceforge.net/projects/eaccelerator/),?[xcache](http://xcache.lighttpd.net/),以及[APC](http://php.net/manual/zh/book.apc.php)。 APC 是 PHP 項目官方支持的,最為活躍,也最容易安裝。 它也提供一個可選的類?[memcached](http://memcached.org/)?的持久化鍵-值對存儲,因此你應使用它。
### 安裝 APC
在 Ubuntu 12.04 上你可以通過在終端中執行以下命令來安裝 APC:
~~~
user@localhost: sudo apt-get install php-apc
~~~
除此之外,不需要進一步的配置。
### 將 APC 作為一個持久化鍵-值存儲系統來使用
APC 也提供了對于你的腳本透明的類似于 memcached 的功能。 與使用 memcached 相比一個大的優勢是 APC 是集成到 PHP 核心的,因此你不需要在服務器上維護另一個運行的部件, 并且 PHP 開發者在 APC 上的工作很活躍。 但從另一方面來說,APC 并不是一個分布式緩存,如果你需要這個特性,你就必須使用 memcached 了。
## 示例
~~~
<?php
// Store some values in the APC cache. We can optionally pass a time-to-live,
// but in this example the values will live forever until they're garbage-collected by APC.
apc_store('username-1532', 'Frodo Baggins');
apc_store('username-958', 'Aragorn');
apc_store('username-6389', 'Gandalf');
// After storing these values, any PHP script can access them, no matter when it's run!
$value = apc_fetch('username-958', $success);
if($success === true)
print($value); // Aragorn
$value = apc_fetch('username-1', $success); // $success will be set to boolean false, because this key doesn't exist.
if($success !== true) // Note the !==, this checks for true boolean false, not "falsey" values like 0 or empty string.
print('Key not found');
apc_delete('username-958'); // This key will no longer be available.
?>
~~~
## 陷阱
* 如果你使用的不是?[PHP-FPM](http://phpbestpractices.justjavac.com/#serving-php)(例如你在使用?[mod_php](http://stackoverflow.com/questions/2712825/what-is-mod-php)?或?[mod_fastcgi](http://www.fastcgi.com/mod_fastcgi/docs/mod_fastcgi.html)), 那么每個 PHP 進程都會有自己獨有的 APC 實例,包括鍵-值存儲。 若你不注意,這可能會在你的應用代碼中造成同步問題。
## 進一步閱讀
* [PHP 手冊:APC](http://php.net/manual/zh/book.apc.php)
* [Laruence:深入理解 PHP 原理之 Opcodes](http://www.laruence.com/2008/06/18/221.html)