开发者

what is the common practice on doing oo in db?

开发者 https://www.devze.com 2023-03-23 13:32 出处:网络
Here is situation.... ... I have a DBManager, which is implement a DBInterface, in the DBInterface, I got 4 method:

Here is situation.... ... I have a DBManager, which is implement a DBInterface, in the DBInterface, I got 4 method:

-create(DBCmd);
-read(DBCmd);
-update(DBCmd);
-delete(DBCmd);

The DBCmd object is responsible for generate the SQL statement, and the DBCmd requires an object in sql statement:

class DBCmd{
    public _constructor($aObj){
    }
    public executeCreate(){
    }
    public executeRead(){
    }
    public executeUpdate(){
    }
    public executeDelete(){
    }

}

The flow will be like this:

aObject ---> put it into DBCmd ----> put the DBCmd in DBManager ---> execute 

But the problems happen when I get some objects related to other tables, for example...a customer have a purchase record, and which purchase record have many items....

So, what do I do in my read method? should I read all the records related to the customer?? Do I need to loop all the items inside the purchase record too? If yes, when I doing read customer, I need to query 3 tables, but some that may not need to see.....it waste the resource...

And I come up with another solution, I make a new set of DBCmd, that allow me to get the related DB items, for example:

class getReleatedPurchaseRecordDBCmd{
    public _constructor($aCustomerObject){
    }
    //.... ....
}

But in this "solution", I got 开发者_StackOverflowsome problems, is I loss the relationship in the object customer...yes, I can read back all the records, get the customer object basically don't know any things about the purchase record....

Some may ask me to do something like this:

class customer{
    //skip other methods...

    public getPurchaseRecords(){
       //query the db
    }

}

It works, but I don't want the object structure have some strong relationship between the db....That's why I come up with the DBCmd stuff...

So, everything seems to be very coupling, how can solve it? Thank you.


for stuff like this i tend to get the count of sub objects with the initial query usually involving sql COUNT and JOIN, then have a seperate getSubObjects command that can be called if needed later. So for example:

$datamodel->getCustomer($id);//or some such method

returns

class Customer{
   $id = 4;
   $recordCount = 5;
   $records = null;
}

I can then use the count for any display stuff as needed, and if i need the records populated call:

$customer->records = $datamodel->getCustomerRecords($customer->id);
0

精彩评论

暂无评论...
验证码 换一张
取 消