SlideShare a Scribd company logo
1 of 20
Advanced Usage of
 Zend_Paginator
   The Dutch PHP BBQ 2009
      Jurriën Stutterheim
About Me

• ZF user since ZF 0.2
• ZF contributor since 2007
• Author and co-author of Zend_Paginator
  and Zend_Feed_Reader
This Presentation

• Short Introduction to Zend_Paginator
• Zend_Paginator & Relational Databases
• Zend_Paginator & Domain Models
• Alternative use-cases
Short Introduction
“Zend_Paginator is a flexible
component for paginating
collections of data and
presenting that data to users.”
- Zend Framework Reference Guide
Primary Design Goals
•   Paginate arbitrary data, not just relational databases

•   Fetch only the results that need to be displayed

•   Do not force users to adhere to only one way of
    displaying data or rendering pagination controls

•   Loosely couple Zend_Paginator to other Zend
    Framework components so that users who wish to
    use it independently of Zend_View, Zend_Db, etc.
    can do so

- Zend Framework Reference Guide
Simple Example
// Create a Paginator that will paginate an
// array with the values 1 to 100
$paginator = new Zend_Paginator(
    new Zend_Paginator_Adapter_Array(range(1, 100))
);
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber(3);
// Echoes numbers 21 to 30
foreach ($paginator as $item) {
   echo $item;
}
// This assumes the view helper has been setup
echo $paginator
Available Adapters
  Out of the box Zend_Paginator supports:
• arrays
• Iterators
• Zend_Db_Select
• Zend_Db_Table_Select
Paginator & Database
• The total number of items is needed to
  calculate the number of pages
• A count-query is executed to determine
  the total number of items the original
  query would retrieve
• Paginator only fetches the rows for the
  current page
The Count Query
The COUNT query for
SELECT * FROM huge_table

is
SELECT COUNT(1) AS
zend_paginator_row_count FROM huge_table

In order to fetch the rows for the current
page:
SELECT * FROM huge_table LIMIT 20, 10
Complex Queries
In case of more complex queries, subqueries
are used instead. Original query:
SELECT *, MAX(rating) AS highest_rating FROM publications
WHERE publication_year > 2006
GROUP BY category, publication_year, author
HAVING highest_rating > 3


Count query:
SELECT COUNT(1) AS zend_paginator_row_count FROM (
    SELECT *, MAX(rating) AS highest_rating FROM publications
    WHERE publication_year > 2006
    GROUP BY category, publication_year, author
    HAVING highest_rating > 3
)
Custom Queries

It’s also possible to use a custom COUNT
query:
// $select contains the query from the last example
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
$adapter->setRowCount(
    $db->select()->from('publication_counts', array(
        Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN =>
        'highest_rating_count'
    ))
);
$paginator = new Zend_Paginator($adapter);
Fixed Page Count

You can specify a fixed page count. No COUNT
query is executed in this case:
// This table has tens of thousands of records
$table = new Zend_Db_Table('publications');
$select = $table->select()->order('rating DESC');
$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
$adapter->setRowCount(500);
$paginator = new Zend_Paginator($adapter);
Paginator & Domain
        Models
• When using a domain model you don’t
  want to pass database rows to your view,
  but rather use them to construct domain
  objects.
• You do however wish to keep the Paginator
  features at your disposal.
• Zend_Paginator supports this using filters.
Filters
• Filter the result from the adapter
• Need to implement Zend_Filter_Interface
• Can be chained if required
• Zend_Filter_Callback allows you to easily
  reuse existing models to construct domain
  objects
Example
class MyObject {
    // Snip...
    public static function factory($rows) {
        $objects = array();
        foreach ($rows as $row) {
            $objects[] = new MyObject($row);
        }
        return $objects;
    }
    public function getFoo() {
        return 'foo';
    }
}
// $select is a Zend_Db_Table_Select object
$paginator = new Zend_Paginator(
    new Zend_Paginator_Adapter_DbTableSelect($select)
);
$paginator->setFilter(new Zend_Filter_Callback(
    array('MyObject', 'factory'))
);
foreach ($paginator as $item) {
    echo $item->getFoo(); // echoes foo
}
Alternative Use-cases


• Batch Processing
• Zend_Entity
Batch Processing
• For example, rebuilding a
  Zend_Search_Lucene search index using a
  large amount data from a database
• Each page contains a relatively large
  number of items
• Main advantage is limited memory usage
  because not all rows are loaded into
  memory at once
Batch Example
public function rebuild()
{
    $paginator = new Zend_Paginator(
        new Zend_Paginator_Adapter_DbTableSelect($this->getSelect())
    );
    $paginator->setCacheEnabled(false);
    // Batch size is 500 records per page/batch
    $paginator->setItemCountPerPage(500);

    $searchIndex = $this->getSearchIndex();

    for ($i = 1; $i <= $paginator->count(); $i++) {
        $items = $paginator->getItemsByPage($i);
        foreach ($items as $item) {
            $searchIndex->addPublication($item);
        }
    }
}
Zend_Entity
• Is a data mapper implementation for ZF
• Currently under heavy development
• Uses Zend_Paginator_AdapterAggregate
• Is used to load subsets of data from the
  datasource to improve performance and
  memory consumption
Finished!

foreach ($questions as $question) {
    $question->answer();
}
$this->bbq(); // o/

More Related Content

Viewers also liked

2008 11 08 Bughuntday
2008 11 08 Bughuntday2008 11 08 Bughuntday
2008 11 08 Bughuntdaynorm2782
 
Production Plan-It Event Gallery
Production Plan-It Event GalleryProduction Plan-It Event Gallery
Production Plan-It Event GalleryHeather Bodington
 
출판문화산업진흥원 공청회 토론(전자출판육성방안)
출판문화산업진흥원 공청회 토론(전자출판육성방안)출판문화산업진흥원 공청회 토론(전자출판육성방안)
출판문화산업진흥원 공청회 토론(전자출판육성방안)Joong Ho Lee
 
Production Plan-It Event Gallery
Production Plan-It Event GalleryProduction Plan-It Event Gallery
Production Plan-It Event GalleryHeather Bodington
 
GRC Presentation
GRC PresentationGRC Presentation
GRC Presentationtevster007
 
S. tevington portfolio 5-2013
S. tevington portfolio 5-2013S. tevington portfolio 5-2013
S. tevington portfolio 5-2013tevster007
 
10 Course Outline Final Student
10 Course Outline Final Student10 Course Outline Final Student
10 Course Outline Final Studentcysps08
 
S. tevington portfolio 5-2013
S. tevington portfolio 5-2013S. tevington portfolio 5-2013
S. tevington portfolio 5-2013tevster007
 

Viewers also liked (8)

2008 11 08 Bughuntday
2008 11 08 Bughuntday2008 11 08 Bughuntday
2008 11 08 Bughuntday
 
Production Plan-It Event Gallery
Production Plan-It Event GalleryProduction Plan-It Event Gallery
Production Plan-It Event Gallery
 
출판문화산업진흥원 공청회 토론(전자출판육성방안)
출판문화산업진흥원 공청회 토론(전자출판육성방안)출판문화산업진흥원 공청회 토론(전자출판육성방안)
출판문화산업진흥원 공청회 토론(전자출판육성방안)
 
Production Plan-It Event Gallery
Production Plan-It Event GalleryProduction Plan-It Event Gallery
Production Plan-It Event Gallery
 
GRC Presentation
GRC PresentationGRC Presentation
GRC Presentation
 
S. tevington portfolio 5-2013
S. tevington portfolio 5-2013S. tevington portfolio 5-2013
S. tevington portfolio 5-2013
 
10 Course Outline Final Student
10 Course Outline Final Student10 Course Outline Final Student
10 Course Outline Final Student
 
S. tevington portfolio 5-2013
S. tevington portfolio 5-2013S. tevington portfolio 5-2013
S. tevington portfolio 5-2013
 

Similar to Advanced Usage of Zend_Paginator

State of search | drupalcamp ghent
State of search | drupalcamp ghentState of search | drupalcamp ghent
State of search | drupalcamp ghentJoris Vercammen
 
Getting up & running with zend framework
Getting up & running with zend frameworkGetting up & running with zend framework
Getting up & running with zend frameworkSaidur Rahman
 
Theming Search Results - How to Make Your Search Results Rock
Theming Search Results - How to Make Your Search Results RockTheming Search Results - How to Make Your Search Results Rock
Theming Search Results - How to Make Your Search Results RockAubrey Sambor
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes ramakesavan
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Jan Helke
 
ASP.NET Session 13 14
ASP.NET Session 13 14ASP.NET Session 13 14
ASP.NET Session 13 14Sisir Ghosh
 
State of search | drupalcon dublin
State of search | drupalcon dublinState of search | drupalcon dublin
State of search | drupalcon dublinJoris Vercammen
 
Multi-tier-performance-analysis-of-ADF-applications.pptx
Multi-tier-performance-analysis-of-ADF-applications.pptxMulti-tier-performance-analysis-of-ADF-applications.pptx
Multi-tier-performance-analysis-of-ADF-applications.pptxKuncoro21
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPOscar Merida
 
MongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkMongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkChris Westin
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHPPaul Jones
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEARMarkus Wolff
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewRyan Cross
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeClay Helberg
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoFu Cheng
 

Similar to Advanced Usage of Zend_Paginator (20)

State of search | drupalcamp ghent
State of search | drupalcamp ghentState of search | drupalcamp ghent
State of search | drupalcamp ghent
 
MongoDb and NoSQL
MongoDb and NoSQLMongoDb and NoSQL
MongoDb and NoSQL
 
Getting up & running with zend framework
Getting up & running with zend frameworkGetting up & running with zend framework
Getting up & running with zend framework
 
Getting up and running with Zend Framework
Getting up and running with Zend FrameworkGetting up and running with Zend Framework
Getting up and running with Zend Framework
 
Theming Search Results - How to Make Your Search Results Rock
Theming Search Results - How to Make Your Search Results RockTheming Search Results - How to Make Your Search Results Rock
Theming Search Results - How to Make Your Search Results Rock
 
Zendcon zray
Zendcon zrayZendcon zray
Zendcon zray
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes Drupal 7 Theming - Behind the scenes
Drupal 7 Theming - Behind the scenes
 
Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']Bye bye $GLOBALS['TYPO3_DB']
Bye bye $GLOBALS['TYPO3_DB']
 
ASP.NET Session 13 14
ASP.NET Session 13 14ASP.NET Session 13 14
ASP.NET Session 13 14
 
State of search | drupalcon dublin
State of search | drupalcon dublinState of search | drupalcon dublin
State of search | drupalcon dublin
 
Multi-tier-performance-analysis-of-ADF-applications.pptx
Multi-tier-performance-analysis-of-ADF-applications.pptxMulti-tier-performance-analysis-of-ADF-applications.pptx
Multi-tier-performance-analysis-of-ADF-applications.pptx
 
Staying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHPStaying Sane with Drupal NEPHP
Staying Sane with Drupal NEPHP
 
MongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkMongoDB's New Aggregation framework
MongoDB's New Aggregation framework
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHP
 
Rapid Prototyping with PEAR
Rapid Prototyping with PEARRapid Prototyping with PEAR
Rapid Prototyping with PEAR
 
Mongo db queries
Mongo db queriesMongo db queries
Mongo db queries
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your View
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 

Recently uploaded

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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...apidays
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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 organizationRadu Cotescu
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

Recently uploaded (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Advanced Usage of Zend_Paginator

  • 1. Advanced Usage of Zend_Paginator The Dutch PHP BBQ 2009 Jurriën Stutterheim
  • 2. About Me • ZF user since ZF 0.2 • ZF contributor since 2007 • Author and co-author of Zend_Paginator and Zend_Feed_Reader
  • 3. This Presentation • Short Introduction to Zend_Paginator • Zend_Paginator & Relational Databases • Zend_Paginator & Domain Models • Alternative use-cases
  • 4. Short Introduction “Zend_Paginator is a flexible component for paginating collections of data and presenting that data to users.” - Zend Framework Reference Guide
  • 5. Primary Design Goals • Paginate arbitrary data, not just relational databases • Fetch only the results that need to be displayed • Do not force users to adhere to only one way of displaying data or rendering pagination controls • Loosely couple Zend_Paginator to other Zend Framework components so that users who wish to use it independently of Zend_View, Zend_Db, etc. can do so - Zend Framework Reference Guide
  • 6. Simple Example // Create a Paginator that will paginate an // array with the values 1 to 100 $paginator = new Zend_Paginator( new Zend_Paginator_Adapter_Array(range(1, 100)) ); $paginator->setItemCountPerPage(10); $paginator->setCurrentPageNumber(3); // Echoes numbers 21 to 30 foreach ($paginator as $item) { echo $item; } // This assumes the view helper has been setup echo $paginator
  • 7. Available Adapters Out of the box Zend_Paginator supports: • arrays • Iterators • Zend_Db_Select • Zend_Db_Table_Select
  • 8. Paginator & Database • The total number of items is needed to calculate the number of pages • A count-query is executed to determine the total number of items the original query would retrieve • Paginator only fetches the rows for the current page
  • 9. The Count Query The COUNT query for SELECT * FROM huge_table is SELECT COUNT(1) AS zend_paginator_row_count FROM huge_table In order to fetch the rows for the current page: SELECT * FROM huge_table LIMIT 20, 10
  • 10. Complex Queries In case of more complex queries, subqueries are used instead. Original query: SELECT *, MAX(rating) AS highest_rating FROM publications WHERE publication_year > 2006 GROUP BY category, publication_year, author HAVING highest_rating > 3 Count query: SELECT COUNT(1) AS zend_paginator_row_count FROM ( SELECT *, MAX(rating) AS highest_rating FROM publications WHERE publication_year > 2006 GROUP BY category, publication_year, author HAVING highest_rating > 3 )
  • 11. Custom Queries It’s also possible to use a custom COUNT query: // $select contains the query from the last example $adapter = new Zend_Paginator_Adapter_DbTableSelect($select); $adapter->setRowCount( $db->select()->from('publication_counts', array( Zend_Paginator_Adapter_DbSelect::ROW_COUNT_COLUMN => 'highest_rating_count' )) ); $paginator = new Zend_Paginator($adapter);
  • 12. Fixed Page Count You can specify a fixed page count. No COUNT query is executed in this case: // This table has tens of thousands of records $table = new Zend_Db_Table('publications'); $select = $table->select()->order('rating DESC'); $adapter = new Zend_Paginator_Adapter_DbTableSelect($select); $adapter->setRowCount(500); $paginator = new Zend_Paginator($adapter);
  • 13. Paginator & Domain Models • When using a domain model you don’t want to pass database rows to your view, but rather use them to construct domain objects. • You do however wish to keep the Paginator features at your disposal. • Zend_Paginator supports this using filters.
  • 14. Filters • Filter the result from the adapter • Need to implement Zend_Filter_Interface • Can be chained if required • Zend_Filter_Callback allows you to easily reuse existing models to construct domain objects
  • 15. Example class MyObject { // Snip... public static function factory($rows) { $objects = array(); foreach ($rows as $row) { $objects[] = new MyObject($row); } return $objects; } public function getFoo() { return 'foo'; } } // $select is a Zend_Db_Table_Select object $paginator = new Zend_Paginator( new Zend_Paginator_Adapter_DbTableSelect($select) ); $paginator->setFilter(new Zend_Filter_Callback( array('MyObject', 'factory')) ); foreach ($paginator as $item) { echo $item->getFoo(); // echoes foo }
  • 16. Alternative Use-cases • Batch Processing • Zend_Entity
  • 17. Batch Processing • For example, rebuilding a Zend_Search_Lucene search index using a large amount data from a database • Each page contains a relatively large number of items • Main advantage is limited memory usage because not all rows are loaded into memory at once
  • 18. Batch Example public function rebuild() { $paginator = new Zend_Paginator( new Zend_Paginator_Adapter_DbTableSelect($this->getSelect()) ); $paginator->setCacheEnabled(false); // Batch size is 500 records per page/batch $paginator->setItemCountPerPage(500); $searchIndex = $this->getSearchIndex(); for ($i = 1; $i <= $paginator->count(); $i++) { $items = $paginator->getItemsByPage($i); foreach ($items as $item) { $searchIndex->addPublication($item); } } }
  • 19. Zend_Entity • Is a data mapper implementation for ZF • Currently under heavy development • Uses Zend_Paginator_AdapterAggregate • Is used to load subsets of data from the datasource to improve performance and memory consumption
  • 20. Finished! foreach ($questions as $question) { $question->answer(); } $this->bbq(); // o/