SlideShare a Scribd company logo
Performance Tuning with
    Zend Framework
        Alan Seiden
      August 23, 2011
                        New York City
                          ZF Meetup
Why a ZF Performance topic?
• I’ve recently helped several clients with
  performance of their ZF apps
• Performance is important to everyone
  today
What we’ll cover tonight
• Question: Does ZF performance differ
  from regular PHP performance?
• Using ZF performance tools
  – Zend_Db_Profiler
  – Zend_Cache
• Other ZF performance optimizations
• Client side measurement and
  optimizations
ZF vs. regular PHP
• ZF is PHP
   – Framework is PHP
   – Your app is PHP
• But it’s more PHP code than your app would use if built
  from scratch
   – Meant to cover common use cases
• With ZF’s MVC, each request goes through routing,
  dispatch
• Each class contains redundant require_once() calls
   – Redundant if you use class autoloader (best performance)
   – Only in ZF 1.x. To be corrected in ZF 2.0
Zend_Db query profiler
• A good reason to use Zend_Db
• Better than manual profiling because you
  won’t miss any queries
• See the actual SQL created by Zend_Db

• One way: Firebug/FirePHP
   – In application.ini:
resources.db.params.profiler.enabled = true
resources.db.params.profiler.class   =
   "Zend_Db_Profiler_Firebug"
Query profiling viewed in FirePHP
Profiling to a log file
// a good place to put this profiling code is in the postDispatch() event of a front
    controller plugin
$db = Zend_Registry::get('db'); // defined in bootstrap

$profiler = $db->getProfiler();
$totalTime    = $profiler->getTotalElapsedSecs();
$queryCount   = $profiler->getTotalNumQueries();

foreach ($profiler->getQueryProfiles() as $i=>$query) {
    $secs = $query->getElapsedSecs();

    $msg = $i . ' - "' . $query->getQuery() . '"';
    $msg .= ', Params: ' . implode(',', $query->getQueryParams());
    $msg .= ', Time: ' . number_format($secs, 6). ' seconds';

    $messages[] = $msg;
}

$log = $queryCount . ' queries in ' . number_format($totalTime, 6)
                   . ' seconds' . "n";

$log .= "Queries:n";
$log .= implode("n", $messages);

$logger = Zend_Registry::get(‘logger’); // defined in bootstrap
$logger->debug($log);
Log file results
2011-08-18T11:34:06-04:00 DEBUG (7): 2 queries in 0.937705 seconds

Queries:
0 - "SELECT COUNT(1) AS "zend_paginator_row_count" FROM "SQHMSTP"
 LEFT JOIN "XUPMSTP" AS "UP1" ON QHAFSR = UP1.UPUID
 LEFT JOIN "XUPMSTP" AS "UP2" ON QHAUSR = UP2.UPUID
 INNER JOIN "XTVMSTP" AS "TV1" ON TV1.TVFLD = 'QHSTAT' and TV1.TVCODE = QHSTAT
 INNER JOIN "XTVMSTP" AS "TV2" ON TV2.TVFLD = 'RPTTYP' and TV2.TVCODE = QHTYPE WHERE
    (QHCOCD = '01')",
 Params: , Time: 0.820897 seconds

1 - "SELECT "SQHMSTP"."QHCASE", "SQHMSTP"."QHCHAS", (QHADMM * 10000 + QHADDD * 100 +
    QHADYY) AS "QHADDT", "SQHMSTP"."QHTYPE", "SQHMSTP"."QHDLR", "SQHMSTP"."QHSTAT",
    "SQHMSTP"."QHRPRF", "SQHMSTP"."QHCREF", "SQHMSTP"."QHSTAT", CASE WHEN (QHSTAT =
    '20' OR (QHSTAT = '40' AND QHRPRF = '')) THEN 1 ELSE 0 END AS "EDITABLE", CASE WHEN
    (QHSTAT = '20' OR QHSTAT = '40') THEN 1 ELSE 0 END AS "DELETABLE", "UP1"."UPNAME"
    AS "QHASSNAME", "UP2"."UPNAME" AS "QHAUSRNAME", "TV1"."TVDESC" AS "QHSTATDESC",
    "TV2"."TVDESC" AS "QHTYPEDESC" FROM "SQHMSTP"
 LEFT JOIN "XUPMSTP" AS "UP1" ON QHAFSR = UP1.UPUID
 LEFT JOIN "XUPMSTP" AS "UP2" ON QHAUSR = UP2.UPUID
 INNER JOIN "XTVMSTP" AS "TV1" ON TV1.TVFLD = 'QHSTAT' and TV1.TVCODE = QHSTAT
 INNER JOIN "XTVMSTP" AS "TV2" ON TV2.TVFLD = 'RPTTYP' and TV2.TVCODE = QHTYPE WHERE
    (QHCOCD = '01') ORDER BY "QHCASE" DESC FETCH FIRST 40 ROWS ONLY",
Params: , Time: 0.116808 seconds
Zend_Cache
• Flexible caching component
• Caches any kind of data: output from PHP
  scripts, complete web pages, ACL objects, query
  results

• Zend_Cache API stores cached data in your
  choice of “backends” (next slide)
Zend_Cache
• Back-ends where cached data can be stored

  –   Zend Server memory or disk cache
  –   Disk (your choice of location)
  –   Memcached
  –   APC
  –   SQLite
  –   Xcache
  –   Static (for generating static files for Apache to serve)
  –   Two-tier fast/slow
Zend_Cache configuration
• Easiest way is in application.ini
    – If you set up your app using Zend_Tool
; front-end
resources.cachemanager.database.frontend.name = Core

; lifetime of 3600 means one hour
resources.cachemanager.database.frontend.options.lifetime = 3600

; automatic_serialization enables non-strings (objects) to be cached
resources.cachemanager.database.frontend.options.automatic_serialization = true

; back-end
; ZendServer_ShMem is Zend Server’s shared memory cache
resources.cachemanager.database.backend.name = "ZendServer_ShMem"
resources.cachemanager.database.backend.customBackendNaming = true
Caching tip for Zend_Db_Table
• Do cache metadata (table/field definitions) if you
  use Zend_Db_Table
• Otherwise you will have a performance hit
• The degree of performance penalty of always
  reading metadata depends on the database
  server
• Play it safe and cache this metadata
   – Assuming tables/fields are relatively constant

// in application.ini
// (“database” cache was defined on previous slide)
resources.db.defaultMetadataCache = "database"
Use an opcode/bytecode cache
• Frameworks add classes and code to an app
• PHP ordinarily must read/interpret/compile all
  that code on each request
• A bytecode cache stores the “compiled”
  bytecode in memory after first execution,
  speeding subsequent runs
• Examples of bytecode caches:
  –   Zend Server’s Optimizer+
  –   APC
  –   XCache
  –   Windows Cache Extension for PHP
ZF Performance Guide
http://framework.zend.com/manual/en/performance.html

• Covers several topics related to ZF performance
• Written by the ZF development team

• Among its recommendations:
   – Avoid “action view helper”: invokes dispatch cycle
      • Replace with view helpers that query a model directly
   – “Use partial() only when really necessary”
      • Partial() clones the whole View object. Use render() if do not
        need a new, clean View object
   – And…
Class loading
• The issues around class loading are given
  special attention in the Performance Guide

• In particular, the “autoloader/require_once()”
  issue is the most frequently discussed
  performance “flaw” of ZF 1.x

• It will be fixed in ZF 2.0

• Details of 1.x “flaw” on next slide......
Autoloader/require_once() issue
• The good:
   – ZF’s autoloader is deemed a well performing component
       • Enabled in /public/index.php like so:
           require_once 'Zend/Loader/Autoloader.php';
           Zend_Loader_Autoloader::getInstance();



• The bad:
   – Even though autoloader loads classes as needed, each class
     executes require_once() statements at the top for each class it
     might need

• Solution: remove require_once() statements from almost
  every ZF class
   – P.S. Matthew Weier O’Phinney says, “this will only improve
     speed if an opcode cache is used.”
How to remove require_once()
Official UNIX way
% cd path/to/ZendFramework/library
% find . -name '*.php' -not -wholename
   '*/Loader/Autoloader.php'  -not -wholename
   '*/Application.php' -print0 |  xargs -0 sed --regexp-
   extended --in-place 's/(require_once)/// 1/g'


Doesn’t remove it from Autoloader.php and
 Application.php because it’s needed there!
Removing require_once() #2
Using PHP
// from http://pastebin.com/wHKJZ68e

chdir (‘mylocationlibraryZend');

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $o_File)
    {
    if (
          '.php' === substr($o_File, -4) &&
          false === strrpos($o_File, '.' . DIRECTORY_SEPARATOR . 'Loader' .
    DIRECTORY_SEPARATOR . 'Autoloader.php') &&
          false === strrpos($o_File, '.' . DIRECTORY_SEPARATOR . 'Application.php')) {
          $s_Code = preg_replace('/^(s*)(require_once)/im', '1// 2',
    file_get_contents($o_File), -1, $i_Replacements);
          if ($i_Replacements > 0) {
                    echo $o_File, ' with ', $i_Replacements, ' replacements.', PHP_EOL;
                    file_put_contents($o_File, $s_Code);
          }
    }
}
Keep an eye on the front end
• Otherwise known as the “client” side
• Includes .js, .css, images, and AJAX calls
• Check it out with Firebug’s “Net” panel or your
  favorite tool

• Example coming up...
HTTP requests




In particular, beware if several AJAX calls must execute on page load
(not shown here) in order for page to render
Apache rewrite rule
.htaccess usually looks like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME}
RewriteRule ^.*$ – [NC,L]
RewriteRule ^.*$ index.php [NC,L]


• Any request that’s not a real file gets routed into
  ZF/PHP
• What’s the performance flaw?
Nonexistent files
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME}
RewriteRule ^.*$ – [NC,L]
RewriteRule ^.*$ index.php [NC,L]


• Nonexistent files (whether favicon.ico or
  my.hacker.getya) get routed to ZF, putting load
  on app server, before generating a 404 not
  found error
• Shouldn’t the web server handle 404?
Solution
• I haven’t found a perfect solution

• To intercept normal “file not found” errors in Apache:
   –   RewriteRule !.(js|ico|gif|jpg|png|css|html|txt|log)$ index.php


• If I’m confident that app URLs shouldn’t have
  any periods/dots in ZF URLs:
   –   RewriteRule !.([^.]+)$ index.php
   – ZF will only receive period-free URLs
   – Apache can then catch “weird” URLs such as
     “w00tw00t.at.ISC.SAN” (I found this in a customer’s Apache log)

• Demonstration on next slide

• Better idea? Send to alan@alanseiden.com
404 Before/after new rule




Before             After
Further learning
• Attend the NYC Web Performance Meetup
• Follow me at @alanseiden
• Keep coming to our ZF meetup:
  http://www.meetup.com/ZendFramework-NYCmetro/

• Attend ZendCon, Oct. 17-20, 2011

• Share your discoveries—you are welcome to present at
  the ZF Meetup
New York City area Zend Framework Meetup
                 http://www.meetup.com/ZendFramework-NYCmetro/
                 Affiliated with http://www.nyphp.org/



Thanks for attending Performance Tuning with Zend Framework
presented on Aug. 23, 2011 by


Alan Seiden      http://www.alanseiden.com
                 alan@alanseiden.com
                 Twitter: @alanseiden




Sign up to hear about all our ZF meetups at
http://www.meetup.com/ZendFramework-NYCmetro/

More Related Content

What's hot

Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
ZendCon
 
Zend Core on IBM i - Security Considerations
Zend Core on IBM i - Security ConsiderationsZend Core on IBM i - Security Considerations
Zend Core on IBM i - Security Considerations
ZendCon
 
Web services on IBM i with PHP and Zend Framework
Web services on IBM i with PHP and Zend FrameworkWeb services on IBM i with PHP and Zend Framework
Web services on IBM i with PHP and Zend Framework
Alan Seiden
 
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
Enrico Zimuel
 
IBM i: Fertile Ground for PHP Developers
IBM i: Fertile Ground for PHP DevelopersIBM i: Fertile Ground for PHP Developers
IBM i: Fertile Ground for PHP Developers
Alan Seiden
 
Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i
Zend by Rogue Wave Software
 
Zend Products and PHP for IBMi
Zend Products and PHP for IBMi  Zend Products and PHP for IBMi
Zend Products and PHP for IBMi
Shlomo Vanunu
 
Browser tools that make web development easier
Browser tools that make web development easierBrowser tools that make web development easier
Browser tools that make web development easier
Alan Seiden
 
Install MariaDB on IBM i - Tips, troubleshooting, and more
Install MariaDB on IBM i - Tips, troubleshooting, and moreInstall MariaDB on IBM i - Tips, troubleshooting, and more
Install MariaDB on IBM i - Tips, troubleshooting, and more
Rod Flohr
 
PHP on Windows - What's New
PHP on Windows - What's NewPHP on Windows - What's New
PHP on Windows - What's New
ZendCon
 
PHP Installed on IBM i - the Nickel Tour
PHP Installed on IBM i - the Nickel TourPHP Installed on IBM i - the Nickel Tour
PHP Installed on IBM i - the Nickel Tour
Rod Flohr
 
Running open source PHP applications on you IBM i
Running open source PHP applications on you IBM iRunning open source PHP applications on you IBM i
Running open source PHP applications on you IBM i
Proximity Group
 
Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016
Clark Everetts
 
PHP and Platform Independance in the Cloud
PHP and Platform Independance in the CloudPHP and Platform Independance in the Cloud
PHP and Platform Independance in the Cloud
ZendCon
 
Zend con 2016 bdd with behat for beginners
Zend con 2016   bdd with behat for beginnersZend con 2016   bdd with behat for beginners
Zend con 2016 bdd with behat for beginners
Adam Englander
 
Sizing your alfresco platform
Sizing your alfresco platformSizing your alfresco platform
Sizing your alfresco platform
Luis Cabaceira
 
Dutch php conference_2010_opm
Dutch php conference_2010_opmDutch php conference_2010_opm
Dutch php conference_2010_opmisnull
 
Edp bootstrapping a-software_company
Edp bootstrapping a-software_companyEdp bootstrapping a-software_company
Edp bootstrapping a-software_companyGanesh Kulkarni
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...
ColdFusionConference
 

What's hot (20)

Zend_Tool: Practical use and Extending
Zend_Tool: Practical use and ExtendingZend_Tool: Practical use and Extending
Zend_Tool: Practical use and Extending
 
Zend Core on IBM i - Security Considerations
Zend Core on IBM i - Security ConsiderationsZend Core on IBM i - Security Considerations
Zend Core on IBM i - Security Considerations
 
Web services on IBM i with PHP and Zend Framework
Web services on IBM i with PHP and Zend FrameworkWeb services on IBM i with PHP and Zend Framework
Web services on IBM i with PHP and Zend Framework
 
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
 
IBM i: Fertile Ground for PHP Developers
IBM i: Fertile Ground for PHP DevelopersIBM i: Fertile Ground for PHP Developers
IBM i: Fertile Ground for PHP Developers
 
Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i
 
Zend Products and PHP for IBMi
Zend Products and PHP for IBMi  Zend Products and PHP for IBMi
Zend Products and PHP for IBMi
 
Browser tools that make web development easier
Browser tools that make web development easierBrowser tools that make web development easier
Browser tools that make web development easier
 
Install MariaDB on IBM i - Tips, troubleshooting, and more
Install MariaDB on IBM i - Tips, troubleshooting, and moreInstall MariaDB on IBM i - Tips, troubleshooting, and more
Install MariaDB on IBM i - Tips, troubleshooting, and more
 
PHP on Windows - What's New
PHP on Windows - What's NewPHP on Windows - What's New
PHP on Windows - What's New
 
PHP Installed on IBM i - the Nickel Tour
PHP Installed on IBM i - the Nickel TourPHP Installed on IBM i - the Nickel Tour
PHP Installed on IBM i - the Nickel Tour
 
Running open source PHP applications on you IBM i
Running open source PHP applications on you IBM iRunning open source PHP applications on you IBM i
Running open source PHP applications on you IBM i
 
Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016Php Dependency Management with Composer ZendCon 2016
Php Dependency Management with Composer ZendCon 2016
 
PHP and Platform Independance in the Cloud
PHP and Platform Independance in the CloudPHP and Platform Independance in the Cloud
PHP and Platform Independance in the Cloud
 
Zend con 2016 bdd with behat for beginners
Zend con 2016   bdd with behat for beginnersZend con 2016   bdd with behat for beginners
Zend con 2016 bdd with behat for beginners
 
Sizing your alfresco platform
Sizing your alfresco platformSizing your alfresco platform
Sizing your alfresco platform
 
Dutch php conference_2010_opm
Dutch php conference_2010_opmDutch php conference_2010_opm
Dutch php conference_2010_opm
 
Edp bootstrapping a-software_company
Edp bootstrapping a-software_companyEdp bootstrapping a-software_company
Edp bootstrapping a-software_company
 
Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...Developing High Performance and Scalable ColdFusion Application Using Terraco...
Developing High Performance and Scalable ColdFusion Application Using Terraco...
 
Cfml features modern_coding
Cfml features modern_codingCfml features modern_coding
Cfml features modern_coding
 

Similar to Performance tuning with zend framework

Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APC
Ben Ramsey
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Site Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariSite Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariJoseph Scott
 
The Solar Framework for PHP 5 (2010 Confoo)
The Solar Framework for PHP 5 (2010 Confoo)The Solar Framework for PHP 5 (2010 Confoo)
The Solar Framework for PHP 5 (2010 Confoo)
Paul Jones
 
php & performance
 php & performance php & performance
php & performance
simon8410
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
毅 吕
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
Võ Duy Tuấn
 
Zend framework: Getting to grips (ZF1)
Zend framework: Getting to grips (ZF1)Zend framework: Getting to grips (ZF1)
Zend framework: Getting to grips (ZF1)
Ryan Mauger
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
Matteo Moretti
 
Tips
TipsTips
Tipsmclee
 
Webinar: Zend framework Getting to grips (ZF1)
Webinar: Zend framework Getting to grips (ZF1)Webinar: Zend framework Getting to grips (ZF1)
Webinar: Zend framework Getting to grips (ZF1)
Ryan Mauger
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
Engine Yard
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data Caching
El Taller Web
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
jimbojsb
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
chartjes
 
Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)
Mathew Beane
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Jérémy Derussé
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...King Foo
 

Similar to Performance tuning with zend framework (20)

Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APC
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Site Performance - From Pinto to Ferrari
Site Performance - From Pinto to FerrariSite Performance - From Pinto to Ferrari
Site Performance - From Pinto to Ferrari
 
The Solar Framework for PHP 5 (2010 Confoo)
The Solar Framework for PHP 5 (2010 Confoo)The Solar Framework for PHP 5 (2010 Confoo)
The Solar Framework for PHP 5 (2010 Confoo)
 
php & performance
 php & performance php & performance
php & performance
 
Top ten-list
Top ten-listTop ten-list
Top ten-list
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
 
Zend framework: Getting to grips (ZF1)
Zend framework: Getting to grips (ZF1)Zend framework: Getting to grips (ZF1)
Zend framework: Getting to grips (ZF1)
 
Scaling PHP apps
Scaling PHP appsScaling PHP apps
Scaling PHP apps
 
Tips
TipsTips
Tips
 
Webinar: Zend framework Getting to grips (ZF1)
Webinar: Zend framework Getting to grips (ZF1)Webinar: Zend framework Getting to grips (ZF1)
Webinar: Zend framework Getting to grips (ZF1)
 
6 tips for improving ruby performance
6 tips for improving ruby performance6 tips for improving ruby performance
6 tips for improving ruby performance
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data Caching
 
Scaling php applications with redis
Scaling php applications with redisScaling php applications with redis
Scaling php applications with redis
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)Z-Ray: A customizable development tool belt (Zendcon 2016)
Z-Ray: A customizable development tool belt (Zendcon 2016)
 
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
 

Recently uploaded

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 

Recently uploaded (20)

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 

Performance tuning with zend framework

  • 1. Performance Tuning with Zend Framework Alan Seiden August 23, 2011 New York City ZF Meetup
  • 2. Why a ZF Performance topic? • I’ve recently helped several clients with performance of their ZF apps • Performance is important to everyone today
  • 3. What we’ll cover tonight • Question: Does ZF performance differ from regular PHP performance? • Using ZF performance tools – Zend_Db_Profiler – Zend_Cache • Other ZF performance optimizations • Client side measurement and optimizations
  • 4. ZF vs. regular PHP • ZF is PHP – Framework is PHP – Your app is PHP • But it’s more PHP code than your app would use if built from scratch – Meant to cover common use cases • With ZF’s MVC, each request goes through routing, dispatch • Each class contains redundant require_once() calls – Redundant if you use class autoloader (best performance) – Only in ZF 1.x. To be corrected in ZF 2.0
  • 5. Zend_Db query profiler • A good reason to use Zend_Db • Better than manual profiling because you won’t miss any queries • See the actual SQL created by Zend_Db • One way: Firebug/FirePHP – In application.ini: resources.db.params.profiler.enabled = true resources.db.params.profiler.class = "Zend_Db_Profiler_Firebug"
  • 7. Profiling to a log file // a good place to put this profiling code is in the postDispatch() event of a front controller plugin $db = Zend_Registry::get('db'); // defined in bootstrap $profiler = $db->getProfiler(); $totalTime = $profiler->getTotalElapsedSecs(); $queryCount = $profiler->getTotalNumQueries(); foreach ($profiler->getQueryProfiles() as $i=>$query) { $secs = $query->getElapsedSecs(); $msg = $i . ' - "' . $query->getQuery() . '"'; $msg .= ', Params: ' . implode(',', $query->getQueryParams()); $msg .= ', Time: ' . number_format($secs, 6). ' seconds'; $messages[] = $msg; } $log = $queryCount . ' queries in ' . number_format($totalTime, 6) . ' seconds' . "n"; $log .= "Queries:n"; $log .= implode("n", $messages); $logger = Zend_Registry::get(‘logger’); // defined in bootstrap $logger->debug($log);
  • 8. Log file results 2011-08-18T11:34:06-04:00 DEBUG (7): 2 queries in 0.937705 seconds Queries: 0 - "SELECT COUNT(1) AS "zend_paginator_row_count" FROM "SQHMSTP" LEFT JOIN "XUPMSTP" AS "UP1" ON QHAFSR = UP1.UPUID LEFT JOIN "XUPMSTP" AS "UP2" ON QHAUSR = UP2.UPUID INNER JOIN "XTVMSTP" AS "TV1" ON TV1.TVFLD = 'QHSTAT' and TV1.TVCODE = QHSTAT INNER JOIN "XTVMSTP" AS "TV2" ON TV2.TVFLD = 'RPTTYP' and TV2.TVCODE = QHTYPE WHERE (QHCOCD = '01')", Params: , Time: 0.820897 seconds 1 - "SELECT "SQHMSTP"."QHCASE", "SQHMSTP"."QHCHAS", (QHADMM * 10000 + QHADDD * 100 + QHADYY) AS "QHADDT", "SQHMSTP"."QHTYPE", "SQHMSTP"."QHDLR", "SQHMSTP"."QHSTAT", "SQHMSTP"."QHRPRF", "SQHMSTP"."QHCREF", "SQHMSTP"."QHSTAT", CASE WHEN (QHSTAT = '20' OR (QHSTAT = '40' AND QHRPRF = '')) THEN 1 ELSE 0 END AS "EDITABLE", CASE WHEN (QHSTAT = '20' OR QHSTAT = '40') THEN 1 ELSE 0 END AS "DELETABLE", "UP1"."UPNAME" AS "QHASSNAME", "UP2"."UPNAME" AS "QHAUSRNAME", "TV1"."TVDESC" AS "QHSTATDESC", "TV2"."TVDESC" AS "QHTYPEDESC" FROM "SQHMSTP" LEFT JOIN "XUPMSTP" AS "UP1" ON QHAFSR = UP1.UPUID LEFT JOIN "XUPMSTP" AS "UP2" ON QHAUSR = UP2.UPUID INNER JOIN "XTVMSTP" AS "TV1" ON TV1.TVFLD = 'QHSTAT' and TV1.TVCODE = QHSTAT INNER JOIN "XTVMSTP" AS "TV2" ON TV2.TVFLD = 'RPTTYP' and TV2.TVCODE = QHTYPE WHERE (QHCOCD = '01') ORDER BY "QHCASE" DESC FETCH FIRST 40 ROWS ONLY", Params: , Time: 0.116808 seconds
  • 9. Zend_Cache • Flexible caching component • Caches any kind of data: output from PHP scripts, complete web pages, ACL objects, query results • Zend_Cache API stores cached data in your choice of “backends” (next slide)
  • 10. Zend_Cache • Back-ends where cached data can be stored – Zend Server memory or disk cache – Disk (your choice of location) – Memcached – APC – SQLite – Xcache – Static (for generating static files for Apache to serve) – Two-tier fast/slow
  • 11. Zend_Cache configuration • Easiest way is in application.ini – If you set up your app using Zend_Tool ; front-end resources.cachemanager.database.frontend.name = Core ; lifetime of 3600 means one hour resources.cachemanager.database.frontend.options.lifetime = 3600 ; automatic_serialization enables non-strings (objects) to be cached resources.cachemanager.database.frontend.options.automatic_serialization = true ; back-end ; ZendServer_ShMem is Zend Server’s shared memory cache resources.cachemanager.database.backend.name = "ZendServer_ShMem" resources.cachemanager.database.backend.customBackendNaming = true
  • 12. Caching tip for Zend_Db_Table • Do cache metadata (table/field definitions) if you use Zend_Db_Table • Otherwise you will have a performance hit • The degree of performance penalty of always reading metadata depends on the database server • Play it safe and cache this metadata – Assuming tables/fields are relatively constant // in application.ini // (“database” cache was defined on previous slide) resources.db.defaultMetadataCache = "database"
  • 13. Use an opcode/bytecode cache • Frameworks add classes and code to an app • PHP ordinarily must read/interpret/compile all that code on each request • A bytecode cache stores the “compiled” bytecode in memory after first execution, speeding subsequent runs • Examples of bytecode caches: – Zend Server’s Optimizer+ – APC – XCache – Windows Cache Extension for PHP
  • 14. ZF Performance Guide http://framework.zend.com/manual/en/performance.html • Covers several topics related to ZF performance • Written by the ZF development team • Among its recommendations: – Avoid “action view helper”: invokes dispatch cycle • Replace with view helpers that query a model directly – “Use partial() only when really necessary” • Partial() clones the whole View object. Use render() if do not need a new, clean View object – And…
  • 15. Class loading • The issues around class loading are given special attention in the Performance Guide • In particular, the “autoloader/require_once()” issue is the most frequently discussed performance “flaw” of ZF 1.x • It will be fixed in ZF 2.0 • Details of 1.x “flaw” on next slide......
  • 16. Autoloader/require_once() issue • The good: – ZF’s autoloader is deemed a well performing component • Enabled in /public/index.php like so: require_once 'Zend/Loader/Autoloader.php'; Zend_Loader_Autoloader::getInstance(); • The bad: – Even though autoloader loads classes as needed, each class executes require_once() statements at the top for each class it might need • Solution: remove require_once() statements from almost every ZF class – P.S. Matthew Weier O’Phinney says, “this will only improve speed if an opcode cache is used.”
  • 17. How to remove require_once() Official UNIX way % cd path/to/ZendFramework/library % find . -name '*.php' -not -wholename '*/Loader/Autoloader.php' -not -wholename '*/Application.php' -print0 | xargs -0 sed --regexp- extended --in-place 's/(require_once)/// 1/g' Doesn’t remove it from Autoloader.php and Application.php because it’s needed there!
  • 18. Removing require_once() #2 Using PHP // from http://pastebin.com/wHKJZ68e chdir (‘mylocationlibraryZend'); foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $o_File) { if ( '.php' === substr($o_File, -4) && false === strrpos($o_File, '.' . DIRECTORY_SEPARATOR . 'Loader' . DIRECTORY_SEPARATOR . 'Autoloader.php') && false === strrpos($o_File, '.' . DIRECTORY_SEPARATOR . 'Application.php')) { $s_Code = preg_replace('/^(s*)(require_once)/im', '1// 2', file_get_contents($o_File), -1, $i_Replacements); if ($i_Replacements > 0) { echo $o_File, ' with ', $i_Replacements, ' replacements.', PHP_EOL; file_put_contents($o_File, $s_Code); } } }
  • 19. Keep an eye on the front end • Otherwise known as the “client” side • Includes .js, .css, images, and AJAX calls • Check it out with Firebug’s “Net” panel or your favorite tool • Example coming up...
  • 20. HTTP requests In particular, beware if several AJAX calls must execute on page load (not shown here) in order for page to render
  • 21. Apache rewrite rule .htaccess usually looks like this: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} RewriteRule ^.*$ – [NC,L] RewriteRule ^.*$ index.php [NC,L] • Any request that’s not a real file gets routed into ZF/PHP • What’s the performance flaw?
  • 22. Nonexistent files RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} RewriteRule ^.*$ – [NC,L] RewriteRule ^.*$ index.php [NC,L] • Nonexistent files (whether favicon.ico or my.hacker.getya) get routed to ZF, putting load on app server, before generating a 404 not found error • Shouldn’t the web server handle 404?
  • 23. Solution • I haven’t found a perfect solution • To intercept normal “file not found” errors in Apache: – RewriteRule !.(js|ico|gif|jpg|png|css|html|txt|log)$ index.php • If I’m confident that app URLs shouldn’t have any periods/dots in ZF URLs: – RewriteRule !.([^.]+)$ index.php – ZF will only receive period-free URLs – Apache can then catch “weird” URLs such as “w00tw00t.at.ISC.SAN” (I found this in a customer’s Apache log) • Demonstration on next slide • Better idea? Send to alan@alanseiden.com
  • 24. 404 Before/after new rule Before After
  • 25. Further learning • Attend the NYC Web Performance Meetup • Follow me at @alanseiden • Keep coming to our ZF meetup: http://www.meetup.com/ZendFramework-NYCmetro/ • Attend ZendCon, Oct. 17-20, 2011 • Share your discoveries—you are welcome to present at the ZF Meetup
  • 26. New York City area Zend Framework Meetup http://www.meetup.com/ZendFramework-NYCmetro/ Affiliated with http://www.nyphp.org/ Thanks for attending Performance Tuning with Zend Framework presented on Aug. 23, 2011 by Alan Seiden http://www.alanseiden.com alan@alanseiden.com Twitter: @alanseiden Sign up to hear about all our ZF meetups at http://www.meetup.com/ZendFramework-NYCmetro/