


Detailed introduction to php caching technology and php caching implementation code_PHP tutorial
Some information, such as information that is often constant but can still change, is placed in the cache to speed up the display. This is very valuable. The so-called cache is generally understood to be some shared information stored on the server. It is between the server and the server. Same as life and death, we can specify the next update time when saving the cache, for example, it should be updated every 5 minutes
Data cache: The data cache mentioned here refers to the database query PHP cache mechanism, each access When entering a page, it will first detect whether the corresponding cached data exists. If it does not exist, it will connect to the database, obtain the data, and serialize the query results and save them to the file. In the future, the same query results will be directly obtained from the cache table or file. get.
The most widely used example is the search function of Discuz, which caches the result ID into a table and searches the cache table first when searching for the same keyword next time.
As a common method, when multiple tables are associated, generate an array and save the contents in the attached table to a field in the main table. When necessary, decompose the array. The advantage of this is that only one table can be read. , the disadvantage is that there will be many more steps to synchronize the two data. The database is always the bottleneck. Trading the hard disk for speed is the key point of this.
Page cache:
Every time you access a page, it will first detect whether the corresponding cached page file exists. If it does not exist, connect to the database, get the data, display the page and generate a cache at the same time. Page file, so that the page file will come into play the next time you visit. (Template engines and some common PHP caching mechanism classes on the Internet usually have this function)
Time-triggered cache:
Check whether the file exists and the timestamp is less than the set expiration time. If the file is modified If the timestamp is greater than the current timestamp minus the expiration timestamp, use the cache, otherwise update the cache.
Content-triggered caching:
Force the PHP cache mechanism to be updated when data is inserted or updated.
Static cache:
The static cache mentioned here refers to static, directly generating text files such as HTML or XML, and regenerating them when there are updates, which is suitable for pages that do not change much. , let’s not talk about it anymore.
The above content is a code-level solution. I directly CP other frameworks and am too lazy to change. The content is similar, it is easy to do, and can be used in several ways, but the following content is for the server End-end caching solutions, non-code level, require the cooperation of multiple parties to achieve
Memory caching:
Memcached is a high-performance, distributed memory object PHP caching mechanism system for Reduce database load and improve access speed in dynamic applications.
PHP buffer:
There are eaccelerator, apc, phpa, xcache. I won’t talk about these. Search a bunch of them and see for yourself. If you know there is such a thing, OK
MYSQL cache:
This is also considered non-code level. Classic databases use this method. Look at the running time below, 0.09xxx and the like
I will post it According to the part of my.ini modified by the guy in blue, the 2G MYISAM table can be around 0.05S. It is said that he has modified it for almost a year
Web cache based on reverse proxy:
Such as Nginx, SQUID, mod_proxy (apache2 and above are divided into mod_proxy and mod_cache)
Examples of NGINX
Use Google to find some PHP caching technology methods
Send me a PHP caching implementation , implements apc and file caching, and inherits Cache_Abstract to call third-party caching tools.
Refer to shindig’s cache class and apc.
Php code
代码如下 | 复制代码 |
class CacheException extends Exception {} /** * Cache abstract class */ abstract class Cache_Abstract { /** * Read cache variable * * * @param string $key cache subscript * @return mixed */ abstract public function fetch($key); /** * Cache variable * * * @param string $key cache variable subscript * @param string $value cache variable value * @return bool */ abstract public function store($key, $value); /** * Delete cache variable * * @param string $key cache index * @return Cache_Abstract */ abstract public function delete($key); /** * Clear (delete) all caches * * @return Cache_Abstract */ abstract public function clear(); /** * Lock cache variable * * @param string $key cache index * @return Cache_Abstract */ abstract public function lock($key); /** * Cache variable unlocking * * @param string $key cache subscript*/ abstract public function unlock($key); /** * Get whether the cache variable is locked * * * @param string $key cache subscript * @return bool */ abstract public function isLocked($key); /** * Make sure it is not locked * Sleep at most $tries times to wait for unlocking, skip and unlock if timeout occurs * * @param string $key cache index */ public function checkLock($key) { if (!$this->isLocked($key)) { return $this; } $tries = 10; $count = 0; do { usleep(200); $count ++; } while ($count isLocked($key)); // 最多做十次睡眠等待解锁,超时则跳过并解锁 $this->isLocked($key) && $this->unlock($key); return $this; } } /** * APC extended cache implementation * * * @category Mjie * @package Cache * @author Liushui Mengchun * @copyright Copyright (c) 2008- * @license New BSD License * @version $Id: Cache/Apc.php version number 2010-04-18 23:02 cmpan $ */ class Cache_Apc extends Cache_Abstract { protected $_prefix = 'cache.mjie.net'; public function __construct() { if (!function_exists('apc_cache_info')) { throw new CacheException('apc extension didn't installed'); } } /** * Save cache variable * * @param string $key * @param mixed $value * @return bool */ public function store($key, $value) { return apc_store($this->_storageKey($key), $value); } /** * Read cache * * * @param string $key * @return mixed */ public function fetch($key) { return apc_fetch($this->_storageKey($key)); } /** * Clear cache * * @return Cache_Apc */ public function clear() { apc_clear_cache(); return $this; } /** * Delete cache unit * * * @return Cache_Apc */ public function delete($key) { apc_delete($this->_storageKey($key)); return $this; } /** * Whether the cache unit is locked * * * @param string $key * @return bool */ public function isLocked($key) { if ((apc_fetch($this->_storageKey($key) . '.lock')) === false) { return false; } return true; } /** * 锁定缓存单元 * * @param string $key * @return Cache_Apc */ public function lock($key) { apc_store($this->_storageKey($key) . '.lock', '', 5); return $this; } /** * Cache unit unlocked * * * @param string $key * @return Cache_Apc */ public function unlock($key) { apc_delete($this->_storageKey($key) . '.lock'); return $this; } /** * Full cache name * * * @param string $key * @return string */ private function _storageKey($key) { return $this->_prefix . '_' . $key; } } /** * File cache implementation * * * @category Mjie * @package Cache * @author Liushui Mengchun * @copyright Copyright (c) 2008- < ;cmpan(at)qq.com> * @license New BSD License * @version $Id: Cache/File.php Version number 2010-04-18 16:46 cmpan $ */ class Cache_File extends Cache_Abstract { public $useSubdir = false; protected $_cachesDir = 'cache'; public function __construct() { if (defined('DATA_DIR')) { $this->_setCacheDir(DATA_DIR . '/cache'); } } /** * Get cached file * * * @param string $key * @return string */ protected function _getCacheFile($key) { $subdir = $this->useSubdir ? substr($key, 0, 2) . '/' : ''; return $this->_cachesDir . '/' . $subdir . $key . '.php'; } /** * Read cache variables * To prevent information leakage, the cache file format is a php file and starts with "" * * @param string $ key cache index * @return mixed */ public function fetch($key) { $cacheFile = self::_getCacheFile($key); if (file_exists($cacheFile) && is_readable($cacheFile)) { // include 方式 //return include $cacheFile; // 系列化方式 return unserialize(@file_get_contents($cacheFile, false, NULL, 13)); } return false; } /** * Cache variable * To prevent information leakage, the cache file format is a php file and starts with "" * * @param string $key cache Variable subscript * @param string $value The value of the cache variable * @return bool */ public function store($key, $value) { $cacheFile = self::_getCacheFile($key); $cacheDir = dirname($cacheFile); if(!is_dir($cacheDir)) { if(!@mkdir($cacheDir, 0755, true)) { throw new CacheException("Could not make cache directory"); } } // 用include方式 //return @file_put_contents($cacheFile, ' return @file_put_contents($cacheFile, '' . serialize($value)); } /** * Delete cache variable * * @param string $key cache subscript * @return Cache_File */ public function delete($key) { if(emptyempty($key)) { throw new CacheException("Missing argument 1 for Cache_File::delete()"); } $cacheFile = self::_getCacheFile($key); if(!@unlink($cacheFile)) { throw new CacheException("Cache file could not be deleted"); } return $this; } /** * Whether the cache unit has been locked * * * @param string $key * @return bool */ public function isLocked($key) { $cacheFile = self::_getCacheFile($key); clearstatcache(); return file_exists($cacheFile . '.lock'); } /** * 锁定 * * @param string $key * @return Cache_File */ public function lock($key) { $cacheFile = self::_getCacheFile($key); $cacheDir = dirname($cacheFile); if(!is_dir($cacheDir)) { if(!@mkdir($cacheDir, 0755, true)) { if(!is_dir($cacheDir)) { throw new CacheException("Could not make cache directory"); } ; } /** * 解锁 * * @param string $key * @return Cache_File */ public function unlock($key) { $cacheFile = self::_getCacheFile($key); @unlink($ cacheFile . '.lock'); return |
www.bkjia.com
true

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment
