phpeveryday.com

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


OOP Pattern - Registry: Embedded Registry

Tag: oop, pattern, registry, embedded   Category: PHP Classes
post: 21 Feb 2008 read: 592


PHP Registry Pattern Step By Step Tutorial - Part 3:It will be more powerfull if we combine Registry as feature of another object. This post will talk about sample use Registry and Factory pattern to maintenance a cache of objects (instead of creating them again).

<?php
class Registry{
  var $_store = array();
  
  function isvalid($key){
    return array_key_exists($key, $this->_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 Registry;
	  return $instance[0];
	}
  }
}

class CarList{
  var $registry;
  
  function CarList(){
    $this->registry =& Registry::getInstance();
  }

  function addCar($brand, $type){
    $this->registry->set($brand, $type);
  }  
  
  function FindCar($brand){    
    if(!$this->registry->isValid($brand)){
	  // if no key with this brand
	  // add this key
	  $this->registry->set($brand,$brand.' is new brand car');
	}
	return $this->registry->get($brand);
  }
}

// TEST IT
$obj = new CarList;
echo "Search #1: ";
echo $obj->FindCar('Honda');
echo "<br>";

$obj->addCar('Nissan','Livina');
echo "Search #2: ";
echo $obj->FindCar('Nissan');

// OUTPUT
// Search #1: Honda is new brand car
// Search #2: 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

1 Responses to OOP Pattern - Registry: Embedded Registry:

I think you should publish comments even you are not agree with author!

why dont you publish my last comment?!

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


615
posting