ThinkPHP cache fast cache and dynamic cache
thinkPHP's F method can only be used to cache simple data types and does not support validity periods and cached objects. The S() cache method supports validity period, also known as dynamic cache method. This article is the editor’s daily compilation of thinkphp caching methods. Friends who are interested in thinkphp caching methods should learn together.
The system’s default caching method is File caching. We can define other caches in the project configuration file. Method, for example, modify the default caching method to Xcache (of course, your environment needs to support Xcache)
For the problem of a large number of files in the cache directory under the File mode cache due to too much cached data, ThinkPHP A solution is also given to enable hash subdirectory caching.
'DATA_CACHE_SUBDIR'=>true
You can also set the level of the hash directory. For example,
'DATA_PATH_LEVEL'=>2
can automatically create multi-layer subdirectories for caching based on the hash of the cache identifier.
The S method supports cache validity period. In many cases, we may not need the concept of validity period, or using file mode caching can meet the requirements, so the system also provides a fast cache specifically for file mode. Cache method F method. The F method can only be used to cache simple data types, and does not support validity periods and cache objects. Use the following:
//快速缓存Data数据,默认保存在DATA_PATH目录下面 F('data',$data); //快速缓存Data数据,保存到指定的目录 F('data',$data,TEMP_PATH); F('user/data',$data); //删除缓存数据 F('data',null); //获取缓存数据 $data=F('data');
Configuration file config.php
//动态缓存,缓存文件存在于\Runtime\Temp 'DATA_CACHE_TYPE'=>'file', 'DATA_CACHE_TIME'=>'3600', //'DATA_CACHE_SUBDIR'=>true,//开启子目录 //'DATA_CACHE_LEVEL'=>3,//设置子目录的层次
Action file:
function view(){ //缓存 //$cache=Cache::getInstance('缓存方式','缓存参数'); //$cache=Cache::getInstance('Xcache',array('expire'=>60)); //$cache->set('名字','值');或者$cache->name='值'; //$value=$cache->get('名字');或者$value=$cache->name; //$cache->rm('名字');或者unset($cache->name); //S('名字','数据','3600','类型')缓存快捷方法 $user=M('haodetong'); $value=S('list'); if(empty($value)){ $list=$user->select(); S('list',$list,3600); echo '这个是直接从数据库中读取的文件'; dump($list); }else{ echo '这个是缓存文件'; dump($value); } }
As shown below when visiting for the first time:
As shown after refreshing again:
The following is a separate introduction to the fast caching of the F method in ThinkPHP
The file mode caching can meet the requirements, so the system also provides a fast caching dedicated to the file mode. Cache method F method
$path="../Public/Runtime/"; $str="asdfasdfasdaaaaaaaaaaaaaaaaaaaaaa"; F("str/andy",$str,$path);
In this way, the content of the $str string is placed in the file of ../Public/Runtime/str/andy.php and the file of
andy.php The content is as follows:
<?php return 'asdfasdfasdaaaaaaaaaaaaaaaaaaaaaa'; ?>
The following code is an overview of ThinkPHP caching method S()
thinkPHP’s F method can only be used to cache simple data Type, expiration and cache objects are not supported. The S() cache method supports validity period, also known as the dynamic cache method. The usage example is as follows:
The code is as follows:
// 使用data标识缓存$Data数据 S('data',$Data); //前面的是缓存标示,后面的是缓存的数据
The code is as follows:
// 缓存$Data数据3600秒 S('data',$Data,3600);
The code is as follows:
// 删除缓存数据 S('data',NULL); //第一个参数时缓存的标识名
The code is as follows:
$cache=S($cachename);//设置缓存标示 // 判断是否有这个查询缓存 if(!$cache){ //$cache 中是缓存的标示(每个查询都对应一个缓存 即 不同的查询有不同的缓存) $cache=$video->where($map)->order($order)->limit($limit)->select(); foreach($cache as $key=>$value){ $userlist=$user->where("id=".$value['user_id'])->find(); $cache[$key]["nickname"]=$userlist['nickname']; } S($cachename,$cache,3600); //设置缓存的生存时间 } S($cachename,NULL); //删除缓存
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Analysis on ThinkPHP’s implementation of static caching and dynamic caching
##
The above is the detailed content of ThinkPHP cache fast cache and dynamic cache. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

WSL2isthenewstandardforseriousPHPdevelopmentonWindows.1.InstallWSL2withUbuntuusingwsl--install,thenupdatewithsudoaptupdate&&sudoaptupgrade-y,keepingprojectsintheLinuxfilesystemforoptimalperformance.2.InstallPHP8.3andComposerviaOndřejSurý’sPPA
