tags:

views:

40

answers:

2

Using a very simple set of objects for this example in PHP.

Lets say:

ObjectA:

Properties: DescId;

Methods: getListofData();

ObjectB:

Properties: DescId;DescName;

Methods: getDescNameById();

What I want to know is what is the best way to get the DescName from ObjectB when ObjectA is the one calling the function from within a loop.

I'm thinking that I need to instantiate ObjectB (as New) and then pass in the ObjectA.DescId into the ObjectB.getDescNameById method.

For example:

class objectA {

      function getListOfData(){
            $myObjB= new objectB();
                while ... 
                {
                    $myObjB->descId = $row["descId"];
                    $myDescName = $myObjB->getDescNameById();
                     ...
                     $i++;
                }
      }
}

I'm pretty sure the above will work but I'm not sure if it is the right way, or even if there are other ways of doing this. Is there a name for this type of thing? Some one mentioned Lazy Loading. Is that what this is in PHP?

+2  A: 

Bear in mind that your question needs some expansion.

A class is a recipe. An object is the actual dish made with that recipe.

So, if you need to know how the recipe tastes, you need to actually cook something.

At design time, you're typically thinking about the classes. I.e. When you plan a dinner, you think about what you want to serve, in terms of recipes, not in term of finished dishes. (You don't have the dishes until you cook them.) That said, you may take into account that some recipes are difficult to execute and so a risky proposition to serve.

Does that make it sense?

Some questions to ask yourself about the design:

Do you even need ObjectA, as they both store an id with the same name? (Presumably, they're tied together.)

What's the difference between the two?

Can this be combined into one object?

These depends on what the methods do and what the id actually is.

George Marian
Fair enough... As you are alluding to I built these objects very closely in design to the table structures. I think you are suggesting I actually design an object to what it is rather than the where the data comes from.
Jeff V
@Jeff Yes, very much so: `you are suggesting I actually design an object to what it is rather than the where the data comes from`
George Marian
+1  A: 

In addition, you should try to assign any required information during class b's constructor.

So:

$myObjB->descId = $row["descId"];
$myDescName = $myObjB->getDescNameById();

Might become:

$myObjB = new Object_B($row["descId"]);
$myDescName = $myObjB->get_description();

This helps keep B as self-contained as possible, which is usually one of the goals of OO.

Jhong