Jump to content

Best way to handle a collection of objects?


EricIsGood

Recommended Posts

I've been googling for hours, and I can't seem to find any 'best practice' information on this.

 

In my example, I have a Notice object, and a Notices object.

 

Notices is simply a collection of Notice objects.  In the future I may want to have more control over adding / removing notices from the collection, but for now the raw access is fine.

 

My example code is bellow.  My questions are:

1. is this the best way to go about a collection of objects?

2. if I want more control over Notices (plural) such as restricting the type of Notice (singular) that can be added to the collection, could I do that without refactoring code outside the class?

3. would it be better design to only allow the Notices class to access the Notice class?

 

Thanks for your help.

 

-Eric

 


$notices = new Notices();

if (trim($userName) == "")
    {
        $notice = new Notice('userName','Please choose a username.');
        $this->notices->notice[0] = $notice;
    }

if (trim($userName) == "Webmaster")
    {
        $notice = new Notice('userName','Reserved Name.');
        $this->notices->notice[1] = $notice;
    }
echo $this->notices->notice[0]->text;
echo $this->notices->notice[1]->text;


class Notices
{
public  $notice = array();	
}

class Notice
{
public $type;
public $text;

public function __construct($type, $text)
{
	$this->type = $type;
	$this->text = $text;
}
}

Try something along the lines of this:

 

<?php
class Notices{
private $notice=array();

public function get($key){
	//Accepts an array of keys
	if(is_array($key)){
		$return=array();
		foreach($key as $notice){
			$return[$notice]=$this->notice[$notice];
		}
		return $return;
	}
	return $this->notice[$key];
}

public function add($key, $object){
	if(!array_key_exists($key, $this->notice)){
		$this->notice[$key]=$object;
		return true;
	}
	throw new Exception('Key already exists');
}
}
?>

 

Chris,

 

Thanks for the reply.

 

This works fine in my current case.

 

For future reference, if I had a very large collection of objects, and wanted to let external code iterate through them, would this be substantially slower than direct access to an array?

 

Thanks,

 

-Eirc

A function call would of course be slower than direct variable [in this case an array, which would be yet slower than a normal {used in this context as int, string, so on} variable] access.

 

 

Unless you have a huge amount of calls to add() or get() you should be fine.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.