SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Caching Basics in PHP
Presented at
The beauty of Web
phpXperts seminar 2010
What is Caching?
“A cache is a temporary storage area 
where frequently accessed data can be 
stored for rapid access.”
Why do we need it?
●
To reduce the number or retrieval queries 
made to a database
●
To reduce the number of requests made to 
external services
●
To reduce the time spent computing data
●
To reduce filesystem access
A basic example
●
A Post
● 23 comments
● Sidebar Contents
●
Navigations
● Categories
● Much more...
We have to load -
1. Check if already cached
if(the resource is cached) {
Just display it.
}
// TOP of your script
$cachefile = 'cache/'.basename($_SERVER['SCRIPT_URI']);
// Serve from the cache if exist
if (file_exists($cachefile)) {
include($cachefile);
exit;
}
2. Generate content and cache
else{
Get the resource, Display it and Cache.
}
ob_start(); // start the output buffer
// – Your normal PHP script and HTML content here –
// BOTTOM of your script
// save the contents of output buffer to the file
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush(); // Send the output to the browser
3. Expire the cache
●
Event/Trigger
●
Setting a time
if(new comment || post edited) {
Expire cache for this post
}
$cachetime = 120 * 60; // 2 hours
// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile)
&& (time() - $cachetime < filemtime($cachefile))) {
include($cachefile);
Exit;
}
So, It was simple. right?
Request
Output
Cache
Compute
Miss
Hit
Store
1
2
3
4
Request
Your question is ...
My pages always have an ever changing content
and cannot be cached in their entirety
Different Caching Approaches
● Full page caching
● Granular page caching
● Content pre­generation
● Opcode caching
● SQL query caching
● Browser caching
● Object/Variable caching 
Everybody is doing it!
●
Zend Framework
●
CakePHP
●
Kohana
●
Symfony
●
...
●
Drupal (modules)
●
Wordpress (wp­cache)
●
Joomla (modules)
●
PhpBB
●
Magento
●
...
Frameworks                CMSs
What to cache?
Anything that...
● you don't want to fetch or compute every time your code runs.
● isn't going to change very often
To find them, monitor ­
● Queries
● Page loads
● Web Analytics
Where to Cache?
●
Local Database faster than Remote Database *
●
Local Disk faster than Database*
●
RAM faster than Disk*
* Some conditions apply
APC
●
APC: Alternative PHP Cache
●
Free, Open Source Opcode Cache
●
Content / Object caching
●
Simple installation
●
Stores to local, shared memory
●
Going to be released as part of PHP6
Installation
Basic PECL (http://pecl.php.net)
pecl install apc
Ubuntu/LinuxMint
apt­get install php5­apc
Windows
(http://pecl4win.php.net )
extension=php_apc.dll
A Quick Benchmark
PHP Native PHP w/APC
Concurrency Level 10
Time taken for tests 60 seconds
Complete requests 298 914
Total transferred 643,149 bytes 1,962,675 bytes
HTML transferred 516,971 bytes 1,582,035 bytes
Requests per second 4.91 [#/sec] 15.21 [#/sec]
Time per request 2035.405 [ms] 657.623 [ms]
Time per request
(mean, across all concurrent requests)
203.541 [ms] 65.762 [ms]
Transfer rate 10.35 [KB/s] received 31.88 [KB/s] received
How? Opcode caching
Scanning
Lexing
Parsing
Compilation
Object caching
● apc_add() / apc_store() ­ Cache a variable
● apc_fetch() ­ Fetch a stored variable from the cache 
● apc_delete() ­ Removes a stored variable from the 
cache
Monitor apc.php
I am...
http://ajaxray.com | http://www.facebook.com/ajaxray | http://twitter.com/ajaxray
Anis uddin Ahmad
Co­Founder, WNeeds
http://ajaxray.com | anisniit@gmail.com 
Thank you!
?
APC Developers
● George Schlossnagle
● Daniel Cowgill
● Rasmus Lerdorf
● Gopal Vijayaraghavan
● Edin Kadribasic
● Ilia Alshanetsky
● Marcus Börger
● Sara Golemon

Más contenido relacionado

La actualidad más candente

CHI - YAPC NA 2012
CHI - YAPC NA 2012CHI - YAPC NA 2012
CHI - YAPC NA 2012
jonswar
 
CHI-YAPC-2009
CHI-YAPC-2009CHI-YAPC-2009
CHI-YAPC-2009
jonswar
 
Integration with hdfs using WebDFS and NFS
Integration with hdfs using WebDFS and NFSIntegration with hdfs using WebDFS and NFS
Integration with hdfs using WebDFS and NFS
Christophe Marchal
 
SQL Server Integration Services Tips & Tricks
SQL Server Integration Services Tips & TricksSQL Server Integration Services Tips & Tricks
SQL Server Integration Services Tips & Tricks
Guillermo Caicedo
 

La actualidad más candente (20)

Zend Con 2008 Slides
Zend Con 2008 SlidesZend Con 2008 Slides
Zend Con 2008 Slides
 
CHI - YAPC NA 2012
CHI - YAPC NA 2012CHI - YAPC NA 2012
CHI - YAPC NA 2012
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
Memcached
MemcachedMemcached
Memcached
 
CHI-YAPC-2009
CHI-YAPC-2009CHI-YAPC-2009
CHI-YAPC-2009
 
Drupal feature proposal: two new stream-wrappers
Drupal feature proposal: two new stream-wrappersDrupal feature proposal: two new stream-wrappers
Drupal feature proposal: two new stream-wrappers
 
Boost your website by running PHP on Nginx
Boost your website by running PHP on NginxBoost your website by running PHP on Nginx
Boost your website by running PHP on Nginx
 
Caching Data For Performance
Caching Data For PerformanceCaching Data For Performance
Caching Data For Performance
 
1
11
1
 
Integration with hdfs using WebDFS and NFS
Integration with hdfs using WebDFS and NFSIntegration with hdfs using WebDFS and NFS
Integration with hdfs using WebDFS and NFS
 
Fluentd and WebHDFS
Fluentd and WebHDFSFluentd and WebHDFS
Fluentd and WebHDFS
 
WebHDFS at King - May 2014 Hadoop MeetUp
WebHDFS at King - May 2014 Hadoop MeetUpWebHDFS at King - May 2014 Hadoop MeetUp
WebHDFS at King - May 2014 Hadoop MeetUp
 
04 web optimization
04 web optimization04 web optimization
04 web optimization
 
PHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on NginxPHP conference Berlin 2015: running PHP on Nginx
PHP conference Berlin 2015: running PHP on Nginx
 
Running php on nginx
Running php on nginxRunning php on nginx
Running php on nginx
 
NginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniquesNginX - good practices, tips and advanced techniques
NginX - good practices, tips and advanced techniques
 
Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!Slow Database in your PHP stack? Don't blame the DBA!
Slow Database in your PHP stack? Don't blame the DBA!
 
eZ Publish Cluster Unleashed
eZ Publish Cluster UnleashedeZ Publish Cluster Unleashed
eZ Publish Cluster Unleashed
 
SQL Server Integration Services Tips & Tricks
SQL Server Integration Services Tips & TricksSQL Server Integration Services Tips & Tricks
SQL Server Integration Services Tips & Tricks
 
Running PHP on Nginx
Running PHP on NginxRunning PHP on Nginx
Running PHP on Nginx
 

Destacado

Big Data in Real-Time at Twitter
Big Data in Real-Time at TwitterBig Data in Real-Time at Twitter
Big Data in Real-Time at Twitter
nkallen
 
6 basic steps of software development process
6 basic steps of software development process6 basic steps of software development process
6 basic steps of software development process
Riant Soft
 

Destacado (15)

Scalability
ScalabilityScalability
Scalability
 
Developing better PHP projects
Developing better PHP projectsDeveloping better PHP projects
Developing better PHP projects
 
Seminar: PHP Developer for Dummies
Seminar: PHP Developer for DummiesSeminar: PHP Developer for Dummies
Seminar: PHP Developer for Dummies
 
ORO Meetups - Doctrine Events
ORO Meetups - Doctrine EventsORO Meetups - Doctrine Events
ORO Meetups - Doctrine Events
 
Building Large Scale Javascript Application
Building Large Scale Javascript ApplicationBuilding Large Scale Javascript Application
Building Large Scale Javascript Application
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql Injection Myths and Fallacies
Sql Injection Myths and FallaciesSql Injection Myths and Fallacies
Sql Injection Myths and Fallacies
 
Gitlab Training with GIT and SourceTree
Gitlab Training with GIT and SourceTreeGitlab Training with GIT and SourceTree
Gitlab Training with GIT and SourceTree
 
facebook architecture for 600M users
facebook architecture for 600M usersfacebook architecture for 600M users
facebook architecture for 600M users
 
Big Data in Real-Time at Twitter
Big Data in Real-Time at TwitterBig Data in Real-Time at Twitter
Big Data in Real-Time at Twitter
 
List of Software Development Model and Methods
List of Software Development Model and MethodsList of Software Development Model and Methods
List of Software Development Model and Methods
 
6 basic steps of software development process
6 basic steps of software development process6 basic steps of software development process
6 basic steps of software development process
 

Similar a Caching basics in PHP

Drupal caching
Drupal cachingDrupal caching
Drupal caching
Exove
 
Share point 2013 distributed cache
Share point 2013 distributed cacheShare point 2013 distributed cache
Share point 2013 distributed cache
Michael Nokhamzon
 
Site Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariSite Performance - From Pinto to Ferrari
Site Performance - From Pinto to Ferrari
Joseph Scott
 

Similar a Caching basics in PHP (20)

Challenges when building high profile editorial sites
Challenges when building high profile editorial sitesChallenges when building high profile editorial sites
Challenges when building high profile editorial sites
 
Drupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case StudyDrupal Performance - SerBenfiquista.com Case Study
Drupal Performance - SerBenfiquista.com Case Study
 
Caching. api. http 1.1
Caching. api. http 1.1Caching. api. http 1.1
Caching. api. http 1.1
 
Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APC
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
PHPCR e API Platform: cosa significa davvero sviluppare un CMF con Symfony
PHPCR e API Platform: cosa significa davvero sviluppare un CMF con SymfonyPHPCR e API Platform: cosa significa davvero sviluppare un CMF con Symfony
PHPCR e API Platform: cosa significa davvero sviluppare un CMF con Symfony
 
Drupal caching
Drupal cachingDrupal caching
Drupal caching
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
 
Share point 2013 distributed cache
Share point 2013 distributed cacheShare point 2013 distributed cache
Share point 2013 distributed cache
 
Performance tuning with zend framework
Performance tuning with zend frameworkPerformance tuning with zend framework
Performance tuning with zend framework
 
Mobile & Desktop Cache 2.0: How To Create A Scriptable Cache
Mobile & Desktop Cache 2.0: How To Create A Scriptable CacheMobile & Desktop Cache 2.0: How To Create A Scriptable Cache
Mobile & Desktop Cache 2.0: How To Create A Scriptable Cache
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data Caching
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
Built-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIsBuilt-in query caching for all PHP MySQL extensions/APIs
Built-in query caching for all PHP MySQL extensions/APIs
 
Zend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applicationsZend_Cache: how to improve the performance of PHP applications
Zend_Cache: how to improve the performance of PHP applications
 
Karine bosch caching-spsbe14
Karine bosch caching-spsbe14Karine bosch caching-spsbe14
Karine bosch caching-spsbe14
 
Build Automation of PHP Applications
Build Automation of PHP ApplicationsBuild Automation of PHP Applications
Build Automation of PHP Applications
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 
Site Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariSite Performance - From Pinto to Ferrari
Site Performance - From Pinto to Ferrari
 

Más de Anis Ahmad

Más de Anis Ahmad (6)

Testing in Laravel Framework
Testing in Laravel FrameworkTesting in Laravel Framework
Testing in Laravel Framework
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
VCS for Teamwork - GIT Workshop
VCS for Teamwork - GIT WorkshopVCS for Teamwork - GIT Workshop
VCS for Teamwork - GIT Workshop
 
Freelancing; an alternate career
Freelancing; an alternate careerFreelancing; an alternate career
Freelancing; an alternate career
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Caching basics in PHP