phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


OOP Pattern - Registry: Monostate Registry Pattern

Tag: oop, pattern, registry, monostate   Category: PHP Classes
post: 21 Feb 2008 read: 639


PHP Registry Pattern Step By Step Tutorial - Part 2: This is a variation of registry pattern implementation. Any instance would need access to same array.

see line 11: $this->_store =& $GLOBALS['REGISTRY_STORE']; reference operator binds global array to instance variable $store. This is the key to monostate implementation. Each time $this->_store is used, have impact to global variable.


<?php
define('REGISTRY_STORE','__registry_store_key__');
class CarRegistry{
  var $_store;
  
  function CarRegistry(){
    if(!array_key_exists(REGISTRY_STORE, $GLOBALS)
	   || !is_array($GLOBALS['REGISTRY_STORE'])){
	   $GLOBALS['REGISTRY_STORE'] = array();
	}
    $this->_store =& $GLOBALS['REGISTRY_STORE'];
  }
    
  function set($key, $obj){
    $this->_store[$key] = $obj;
  }
  
  function get($key){
    if(array_key_exists($key, $this->_store)){
		return $this->_store[$key];
	}
  }
  
  function &getInstance(){
    static $instance = array();
	if (!$instance){
	  $instance[0] =& new CarRegistry;
	  return $instance[0];
	}else{
		echo "error";
	}
	
  }
  
  function test(){
    print($this->store);
  }
}

// TEST IT
$reg =& CarRegistry::getInstance();

$key = 'honda';
$value = array('Jazz', 'Stream');
$reg->set($key,$value);

$key = 'nissan';
$value = array('Teranno', 'Livina');
$reg->set($key,$value);

echo "Honda: ".implode(", ",$reg->get('honda'));
echo "</br>";
echo "Nissan: ".implode(", ",$reg->get('nissan'));
echo "</br>";
// show mirror
print_r($GLOBALS['REGISTRY_STORE']);

// OUTPUT
// Honda: Jazz, Stream
// Nissan: Teranno, Livina
// Array ( [honda] => Array ( [0] => Jazz 
//                            [1] => Stream ) 
//           [nissan] => Array ( [0] => Teranno 
//                               [1] => Livina ) ) 
?>


Series this article:
OOP Pattern - Registry: Monostate Registry Pattern
OOP Pattern - Registry: Embedded Registry
CodeIgniter - Form: Adding CSS

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


619
posting