Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Sorry for this really bad title.

I have an object class, and an objectManager class used to get all the objects. (This is an example).

I can create an object with new Object($id);

If the id argument is present then the object make an sql query and fill itself with the data.

I want to make a table of all my objects, displaying their values.

Should i use the objectManager class to make a big SQL query that will return everything I need, or juste get a list of id and then load each object individually in a loop ?

I think that making only one query is better, but the code is really easier to read with the second solution.

What's your favorite method ?

Thanks

share|improve this question

put on hold as too broad by Alma Do, Robert, Nunser, Michael G. Emmons, manouti Sep 3 at 16:07

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

    
I know that this question may be too broad, but sometimes we just need to be pointed in the right direction. Also, if you have a better title, feel free to change it. –  FC' 2 days ago

1 Answer 1

up vote 0 down vote accepted

You should have one query only, and the Objects should then be hydrated with the relevant data without having to pass an ID. You could implement a Hydrate or exchangeArray method:

example:

public function exchangeArray(array $data){
$this->property1=$data['property1'];
$this->property2=$data['property2'];
$this->property3=$data['property3'];
return $this;
}

EDIT

You could also process this in your Object constructor:

public function __construct($argument){

    if(is_numeric($argument)){
    //treat as ID
    return $this->findById($argument);
    }elseif(is_array($argument)){
    //hydrate object without call to DB
    return $this->exchangeArray($argument);
    }
}

You may want to look at the Doctrine project which provides an off the shelf object relational mapper layer:

http://www.doctrine-project.org/projects/orm.html

see also the Repository pattern:

http://martinfowler.com/eaaCatalog/repository.html

share|improve this answer
    
Thanks, it looks like what i'm looking for –  FC' Sep 3 at 12:43
    
You're welcome. I've also improved my answer, please see edit above. You can modify your object class to accept either a numeric ID or an array which would hydrate the object with the given array rather than the DB. Please accept answer if satisfied. –  matwr Sep 3 at 13:07
    
Satisfied. Thanks –  FC' 2 days ago

Not the answer you're looking for? Browse other questions tagged or ask your own question.