Jump to content

[SOLVED] best practices for storing class attributes? as individual vars or in an array?


alexweber15

Recommended Posts

just wondering what the consensus on best practices for storing a multitude of class attributes is?

 

for example i have a Person class that has the following attributes, age, height, hair color, etc the basic php tutorial stuff.. :)

 

is it better to store the attributes as individual variables, ie:

 

public $age, $height, $hairColor;

 

or in an array, ie:

 

public $attributes = array();

$this->attributes[age] = xxxx';

$this->attributes[height] = xxxx';

$this->attributes[hairColor] = xxxx';

 

i realize that using an array is more practical in terms of traversing the attributes and performing operations to them collectively such as validation or strip_tags(), etc... but is there any performance downside?

 

thanks!

 

Alex

Link to comment
Share on other sites

I sometimes cheat and use arrays it saves alot of work when your needing to handle alot of data in a similar way or throw it back to a form.

 

If you retain the structure of a $_POST from a form within an object array you can validate the data and return it to the form with little/no effort where as if you process it into separate object variables you have to return the data into its original structure.

 

Arrays save time but its not necessarily best practice. However if you are adding a product to a store system you are going to want to treat all the data for that product in a similar fashion they wouldn't need different permissions (private $name; public $size;) So what is the actual need other than for "best practice".

 

I say best practice is the practice that makes me the least amount of work.

public function add()
	{
		$this->values = $this->database->antisql($this->values);
		foreach($this->values as $name => $value)
			{
				//remove x and y (image coordinates which are not to be entered into the database)
				$array = array('x', 'y');
				if (!in_array($name, $array))
					{
						$start .= '`'.$name.'`, ';
						$end .= "'".$value."', ";
					}
			}
		$start = substr($start, 0, -2);
		$end = substr($end, 0, -2);
		if ($this->database->query("INSERT INTO `products` ($start) VALUES ($end)"))
			{
				return 1;
			}
		return 0;
	}

Link to comment
Share on other sites

I'm a purist.

 

Hiding implementation is important for a number of things, but most of all encapsulation. Hiding the details of an implementation of an object is really important.

 

What you're talking about now is a Model Object. Model objects are classes which contain a list of private members, and a series of Accessors / mutators to read/write data.  The reason to not make the properties public is simple, you have a finer grain of control if you implement them as methods. Model objects are populated and passed around for a number of reasons:

1) For the presentation layer

2) Application Services to act on the data

3) Persistence layer for saving state.

 

 

Model Objects are generally defined in the following way:

 

<?php

class Person {
    private $age ;
    private $height ;
    private $color ;
   

    public function __construct() {} //blank constructor.

    public function setAge($age) { $this->age = $age; }

    public function setHeight($height) { 
         if (!is_int($height)) return; //do nothing if the height was not set properly,
         $this->height = $height;
    }

    .
    .

    .

    public function getHeight() { return $this->height; }
    public function getAge() { return $this->age; }

}
?>

 

Link to comment
Share on other sites

I'm a purist.

 

Hiding implementation is important for a number of things, but most of all encapsulation. Hiding the details of an implementation of an object is really important.

 

What you're talking about now is a Model Object. Model objects are classes which contain a list of private members, and a series of Accessors / mutators to read/write data.  The reason to not make the properties public is simple, you have a finer grain of control if you implement them as methods. Model objects are populated and passed around for a number of reasons:

1) For the presentation layer

2) Application Services to act on the data

3) Persistence layer for saving state.

 

 

Model Objects are generally defined in the following way:

 

<?php

class Person {
    private $age ;
    private $height ;
    private $color ;
   

    public function __construct() {} //blank constructor.

    public function setAge($age) { $this->age = $age; }

    public function setHeight($height) { 
         if (!is_int($height)) return; //do nothing if the height was not set properly,
         $this->height = $height;
    }

    .
    .

    .

    public function getHeight() { return $this->height; }
    public function getAge() { return $this->age; }

}
?>

 

 

 

Seconded.

Link to comment
Share on other sites

KeeB thanks for the detailed reply dude!

 

i completely agree with you on all points but fail to see how this impacts the decision on whether or not to store the data as a private array or as multiple private variables?

 

the concept of storing private attributes and public get and set methods remains in either case... !

Link to comment
Share on other sites

Well, sure, but.. then you add complexity. If there's a good reason to add this complexity (I'm not sure there is, hence my original post,) no one is going to fault you for doing it.

 

In the end, it's your decision to make. I'm just trying to get you to make the right one :)

Link to comment
Share on other sites

Well, sure, but.. then you add complexity. If there's a good reason to add this complexity (I'm not sure there is, hence my original post,) no one is going to fault you for doing it.

 

In the end, it's your decision to make. I'm just trying to get you to make the right one :)

 

i know and i appreciate it! :)

...plus all those stars under your name suggest you know what you're talking about... ;)  ;D

 

plus i just ran into this nice snippet of code that iterates through class attributes in exactly the same way as i hoped to do with an array, thus rendering the array approach completely useless :)

 

class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';
    protected $protected = 'protected var';
    private   $private   = 'private var';

    function iterateVisible() {
       foreach($this as $key => $value) {
           echo "$key => $value\n";
       }
    }
}

// print only public attributes
$foo = new MyClass();
foreach($foo as $key=>$value){
    echo "$key => $value\n";
}

//print ALL attributes
$foo->iterateVisible();

 

:)

 

didn't realize you could use foreach to iterate through an object's attributes :)

thanks again for your attention! :)

Link to comment
Share on other sites

If you use lot's of classes and don't want to call require each time you want to use one of your classes, either they be static or instanced, use autoload. I do use it in my custom made framework, and it makes things a lot simpler by not polluting my code with lot's of requires :)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.