SlideShare uma empresa Scribd logo
1 de 17
Registry Pattern The with lazy loading goodness Michael Peacock
whois michaelpeacock.co.uk Experienced senior / lead web developer Web Systems Developer for SmithElectric Vehicles US Corp Author of 6 web development books Owner / CTO of CentralAppsLimitedJust launched first beta product: invoicecentral.co.uk Zend Certified Engineer
Commonly used objects and settings... Within Bespoke frameworks and large applications most of the code often needs access to core objects, settings and variables.
...such as Database Access / Abstraction layers Template engines Object for the currently logged in user Objects which perform common tasks, such as email sending or data processing Site settings: path to uploads folder, cache folder, site URL, etc
The solution: Registry Create a registry to store these core objects and settings Provide methods to store and retrieve these objects and settings Pass this object around your application (e.g. To your models and controllers) –or- make it a singleton (yuk)
Registry: basics <?php 	class Registry { 		private $objects = array(); 		private $settings = array(); 		public function __construct(){} public function storeObject( $object, $key ){} 		public function getObject( $key ){} 		public function storeSetting( $setting, $key ){} 		public function getSetting( $key ){} 	} ?>
Registry: concept code public function storeObject( $object, $key ) { 	if( array_key_exists( $key, $this->objects ) ) 	{ 		//throw an exception 	} elseif( is_object( $object ) ) { 	$this->objects[ $key ] = $object; 	} } public function getObject( $key ) { 	if( array_key_exists( $key, $this->objects ) && is_object( $this->objects[ $key ] ) ) 	{ 		return $this->objects[ $key ]; 	} 	else 	{ 		//throw an exception 	} } EASY!
Registry: usage Make your code aware Public function __construct( Registry $registry) { 	$this->registry = $registry; } Store an object $this->registry->storeObject( $template, ‘template’ ); Access your objects $this->registry->getObject(‘template’)->output();
Registry: The good Keeps core objects and settings in one place Makes it easy to access and use these objects and the data or functionality they hold within Common interface for storing, retrieving and managing common objects and settings
Registry: The bad All aspects of your application need to be registry aware...				...though its easy to simply pass the registry via the constructor to other parts of your code Works best with a front controller / single entry point to your application, otherwise you need to duplicate your registry setup throughout your code
Registry: The ugly Bloat! If you rely on the registry too much, you end up with objects or settings which you only use some of the time This takes up additional resources, time and memory to setup and process the objects and settings for each page load, only for them to be used 50% of the time
Registry: de-uglification Make the registry lazy loading Registry is aware of all of its objects Objects are only instantiated and stored when they are first required, and not before Registry knows about core settings/data that is used frequently, and knows how to access other data if/when required
De-uglification:  Make the registry aware of its objects $defaultRegistryObjects = array();  $db = array( 'abstract' => 'database', 'folder' => 'database', 'file' => 'mysql.database', 'class' => 'MySQLDatabase', 'key' => 'db' );  $defaultRegistryObjects['db'] = $db; $template = array( 'abstract' => null, 'folder' => 'template', 'file' => 'template', 'class' => 'Template', 'key' => 'template' );  $defaultRegistryObjects['template'] = $template; $urlp = array( 'abstract' => null, 'folder' => 'urlprocessor', 'file' => 'urlprocessor', 'class' => 'URLProcessor', 'key' => 'urlprocessor' );
De-uglification     If the object isn’t set, load it the lazy way /**  * Get an object from the registry * - facilitates lazy loading, if we haven't used the object yet and it is part of the setup, then require and instantiate it!  * @param String $key * @return Object  */ public function getObject( $key )  {  if( in_array( $key, array_keys( $this->objects ) ) )  { return $this->objects[$key];  } elseif( in_array( $key, array_keys( $this->objectSetup ) ) )  { 	if( ! is_null( $this->objectSetup[ $key ]['abstract'] ) )  	{  require_once( FRAMEWORK_PATH . 'registry/aspects/' . $this->objectSetup[ $key ]['folder'] . '/' . $this->objectSetup[ $key ]['abstract'] .'.abstract.php' );  	} require_once( FRAMEWORK_PATH . 'registry/aspects/' . $this->objectSetup[ $key ]['folder'] . '/' . $this->objectSetup[ $key ]['file'] . '.class.php' );  	$o = new $this->objectSetup[ $key ]['class']( $this );  	$this->storeObject( $o, $key );  	return $o;  } }
De-uglification: settings Apply the same approach to settings / data Query your core settings If the setting requested hasn’t been loaded, load all related settings (works best if you prefix your keys with a group name)
Conclusion Easily access your core objects, functionality and data from anywhere in your application Apply some lazy loading to keep your application running lean Enjoy!
Any questions? www.michaelpeacock.co.uk www.twitter.com/michaelpeacock www.invoicecentral.co.uk

Mais conteúdo relacionado

Mais procurados

3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides
MasterCode.vn
 
Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6
DEEPAK KHETAWAT
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
Erik Hatcher
 
How to? Drupal developer toolkit. Dennis Povshedny.
How to? Drupal developer toolkit. Dennis Povshedny.How to? Drupal developer toolkit. Dennis Povshedny.
How to? Drupal developer toolkit. Dennis Povshedny.
DrupalCampDN
 
Dev8d Apache Solr Tutorial
Dev8d Apache Solr TutorialDev8d Apache Solr Tutorial
Dev8d Apache Solr Tutorial
Sourcesense
 

Mais procurados (19)

3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides
 
L16 Object Relational Mapping and NoSQL
L16 Object Relational Mapping and NoSQLL16 Object Relational Mapping and NoSQL
L16 Object Relational Mapping and NoSQL
 
it's just search
it's just searchit's just search
it's just search
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
 
Visualizing drupalcode06 25-2015
Visualizing drupalcode06 25-2015Visualizing drupalcode06 25-2015
Visualizing drupalcode06 25-2015
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
CakePHP REST Plugin
CakePHP REST PluginCakePHP REST Plugin
CakePHP REST Plugin
 
Custom Database Queries in WordPress
Custom Database Queries in WordPressCustom Database Queries in WordPress
Custom Database Queries in WordPress
 
Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6Basics of Solr and Solr Integration with AEM6
Basics of Solr and Solr Integration with AEM6
 
Lucene for Solr Developers
Lucene for Solr DevelopersLucene for Solr Developers
Lucene for Solr Developers
 
Extending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh PollockExtending the WordPress REST API - Josh Pollock
Extending the WordPress REST API - Josh Pollock
 
Apache Solr Workshop
Apache Solr WorkshopApache Solr Workshop
Apache Solr Workshop
 
Compass Framework
Compass FrameworkCompass Framework
Compass Framework
 
Staging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for DrupalStaging Drupal: Change Management Strategies for Drupal
Staging Drupal: Change Management Strategies for Drupal
 
How to? Drupal developer toolkit. Dennis Povshedny.
How to? Drupal developer toolkit. Dennis Povshedny.How to? Drupal developer toolkit. Dennis Povshedny.
How to? Drupal developer toolkit. Dennis Povshedny.
 
Dev8d Apache Solr Tutorial
Dev8d Apache Solr TutorialDev8d Apache Solr Tutorial
Dev8d Apache Solr Tutorial
 
Introduction to Apache Solr.
Introduction to Apache Solr.Introduction to Apache Solr.
Introduction to Apache Solr.
 
Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 

Semelhante a PHP North East - Registry Design Pattern

Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Nguyen Duc Phu
 
Xml Java
Xml JavaXml Java
Xml Java
cbee48
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
funkatron
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 

Semelhante a PHP North East - Registry Design Pattern (20)

Apache Ant
Apache AntApache Ant
Apache Ant
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
 
eZ Publish Cluster Unleashed
eZ Publish Cluster UnleashedeZ Publish Cluster Unleashed
eZ Publish Cluster Unleashed
 
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
Optimize Site Deployments with Drush (DrupalCamp WNY 2011)
 
Ant
Ant Ant
Ant
 
Ext 0523
Ext 0523Ext 0523
Ext 0523
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.frameworkHanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
Hanoi php day 2008 - 01.pham cong dinh - how.to.build.your.own.framework
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted NewardArchitecture | Busy Java Developers Guide to NoSQL | Ted Neward
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
 
WordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsWordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big words
 
Xml Java
Xml JavaXml Java
Xml Java
 
Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011Symfony CMF - PHP Conference Brazil 2011
Symfony CMF - PHP Conference Brazil 2011
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
REST dojo Comet
REST dojo CometREST dojo Comet
REST dojo Comet
 
Deploy Flex with Apache Ant
Deploy Flex with Apache AntDeploy Flex with Apache Ant
Deploy Flex with Apache Ant
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 

Mais de Michael Peacock

Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
Michael Peacock
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
Michael Peacock
 
Powerful and flexible templates with Twig
Powerful and flexible templates with Twig Powerful and flexible templates with Twig
Powerful and flexible templates with Twig
Michael Peacock
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
Michael Peacock
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
Evolution of a big data project
Evolution of a big data projectEvolution of a big data project
Evolution of a big data project
Michael Peacock
 
Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012
Michael Peacock
 
Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012
Michael Peacock
 
Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012
Michael Peacock
 
PHP Continuous Data Processing
PHP Continuous Data ProcessingPHP Continuous Data Processing
PHP Continuous Data Processing
Michael Peacock
 

Mais de Michael Peacock (20)

Immutable Infrastructure with Packer Ansible and Terraform
Immutable Infrastructure with Packer Ansible and TerraformImmutable Infrastructure with Packer Ansible and Terraform
Immutable Infrastructure with Packer Ansible and Terraform
 
Test driven APIs with Laravel
Test driven APIs with LaravelTest driven APIs with Laravel
Test driven APIs with Laravel
 
Symfony Workflow Component - Introductory Lightning Talk
Symfony Workflow Component - Introductory Lightning TalkSymfony Workflow Component - Introductory Lightning Talk
Symfony Workflow Component - Introductory Lightning Talk
 
Alexa, lets make a skill
Alexa, lets make a skillAlexa, lets make a skill
Alexa, lets make a skill
 
API Development with Laravel
API Development with LaravelAPI Development with Laravel
API Development with Laravel
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
 
Refactoring to symfony components
Refactoring to symfony componentsRefactoring to symfony components
Refactoring to symfony components
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
 
Powerful and flexible templates with Twig
Powerful and flexible templates with Twig Powerful and flexible templates with Twig
Powerful and flexible templates with Twig
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
Vagrant
VagrantVagrant
Vagrant
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Evolution of a big data project
Evolution of a big data projectEvolution of a big data project
Evolution of a big data project
 
Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012Real time voice call integration - Confoo 2012
Real time voice call integration - Confoo 2012
 
Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012Dealing with Continuous Data Processing, ConFoo 2012
Dealing with Continuous Data Processing, ConFoo 2012
 
Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012Data at Scale - Michael Peacock, Cloud Connect 2012
Data at Scale - Michael Peacock, Cloud Connect 2012
 
Supermondays twilio
Supermondays twilioSupermondays twilio
Supermondays twilio
 
PHP & Twilio
PHP & TwilioPHP & Twilio
PHP & Twilio
 
PHP Continuous Data Processing
PHP Continuous Data ProcessingPHP Continuous Data Processing
PHP Continuous Data Processing
 

Último

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)

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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 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
 
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
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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
 
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...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

PHP North East - Registry Design Pattern

  • 1. Registry Pattern The with lazy loading goodness Michael Peacock
  • 2. whois michaelpeacock.co.uk Experienced senior / lead web developer Web Systems Developer for SmithElectric Vehicles US Corp Author of 6 web development books Owner / CTO of CentralAppsLimitedJust launched first beta product: invoicecentral.co.uk Zend Certified Engineer
  • 3. Commonly used objects and settings... Within Bespoke frameworks and large applications most of the code often needs access to core objects, settings and variables.
  • 4. ...such as Database Access / Abstraction layers Template engines Object for the currently logged in user Objects which perform common tasks, such as email sending or data processing Site settings: path to uploads folder, cache folder, site URL, etc
  • 5. The solution: Registry Create a registry to store these core objects and settings Provide methods to store and retrieve these objects and settings Pass this object around your application (e.g. To your models and controllers) –or- make it a singleton (yuk)
  • 6. Registry: basics <?php class Registry { private $objects = array(); private $settings = array(); public function __construct(){} public function storeObject( $object, $key ){} public function getObject( $key ){} public function storeSetting( $setting, $key ){} public function getSetting( $key ){} } ?>
  • 7. Registry: concept code public function storeObject( $object, $key ) { if( array_key_exists( $key, $this->objects ) ) { //throw an exception } elseif( is_object( $object ) ) { $this->objects[ $key ] = $object; } } public function getObject( $key ) { if( array_key_exists( $key, $this->objects ) && is_object( $this->objects[ $key ] ) ) { return $this->objects[ $key ]; } else { //throw an exception } } EASY!
  • 8. Registry: usage Make your code aware Public function __construct( Registry $registry) { $this->registry = $registry; } Store an object $this->registry->storeObject( $template, ‘template’ ); Access your objects $this->registry->getObject(‘template’)->output();
  • 9. Registry: The good Keeps core objects and settings in one place Makes it easy to access and use these objects and the data or functionality they hold within Common interface for storing, retrieving and managing common objects and settings
  • 10. Registry: The bad All aspects of your application need to be registry aware... ...though its easy to simply pass the registry via the constructor to other parts of your code Works best with a front controller / single entry point to your application, otherwise you need to duplicate your registry setup throughout your code
  • 11. Registry: The ugly Bloat! If you rely on the registry too much, you end up with objects or settings which you only use some of the time This takes up additional resources, time and memory to setup and process the objects and settings for each page load, only for them to be used 50% of the time
  • 12. Registry: de-uglification Make the registry lazy loading Registry is aware of all of its objects Objects are only instantiated and stored when they are first required, and not before Registry knows about core settings/data that is used frequently, and knows how to access other data if/when required
  • 13. De-uglification: Make the registry aware of its objects $defaultRegistryObjects = array(); $db = array( 'abstract' => 'database', 'folder' => 'database', 'file' => 'mysql.database', 'class' => 'MySQLDatabase', 'key' => 'db' ); $defaultRegistryObjects['db'] = $db; $template = array( 'abstract' => null, 'folder' => 'template', 'file' => 'template', 'class' => 'Template', 'key' => 'template' ); $defaultRegistryObjects['template'] = $template; $urlp = array( 'abstract' => null, 'folder' => 'urlprocessor', 'file' => 'urlprocessor', 'class' => 'URLProcessor', 'key' => 'urlprocessor' );
  • 14. De-uglification If the object isn’t set, load it the lazy way /** * Get an object from the registry * - facilitates lazy loading, if we haven't used the object yet and it is part of the setup, then require and instantiate it! * @param String $key * @return Object */ public function getObject( $key ) { if( in_array( $key, array_keys( $this->objects ) ) ) { return $this->objects[$key]; } elseif( in_array( $key, array_keys( $this->objectSetup ) ) ) { if( ! is_null( $this->objectSetup[ $key ]['abstract'] ) ) { require_once( FRAMEWORK_PATH . 'registry/aspects/' . $this->objectSetup[ $key ]['folder'] . '/' . $this->objectSetup[ $key ]['abstract'] .'.abstract.php' ); } require_once( FRAMEWORK_PATH . 'registry/aspects/' . $this->objectSetup[ $key ]['folder'] . '/' . $this->objectSetup[ $key ]['file'] . '.class.php' ); $o = new $this->objectSetup[ $key ]['class']( $this ); $this->storeObject( $o, $key ); return $o; } }
  • 15. De-uglification: settings Apply the same approach to settings / data Query your core settings If the setting requested hasn’t been loaded, load all related settings (works best if you prefix your keys with a group name)
  • 16. Conclusion Easily access your core objects, functionality and data from anywhere in your application Apply some lazy loading to keep your application running lean Enjoy!
  • 17. Any questions? www.michaelpeacock.co.uk www.twitter.com/michaelpeacock www.invoicecentral.co.uk