• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best way to design OO classes

[eluser]Jon L[/eluser]
So I've been working with classes/objects for awhile now, and while I can't say I've 100% grasped MVC (I understand the concept, just implementing isn't always fully clear), I feel comfortable working with classes.

Something I've struggled with, is what is the best way to design new classes?

Example: customers

I have two viewpoints when dealing with customers. One is that I would want to be able to focus specifically on a single customer, and the class deals specifically with the currently loaded customer

The other is that I may want to do large scale selects, updates, etc, to customers. I don't want to have to do individual queries per customer (which would be the case using the previous viewpoint), as that's not efficient, but I *do* want to ensure that all changes to the customers are processed by the managing class, so it can execute any triggers if needed, based on the data that's changing.

What do you do for situations like this? Do you favor the focused single-customer view, or do you favor the large scale overview, or have you found a good solution for dealing with both?

in my point of view, you need to define your Customer class, and model will be responsible for fetching,processing and saving changes. in simple words you need to follow Data Mapper pattern.

so in model you would have methods like, fetch($params),proccess($object),save($object).
and your customer class would probably be a custom data type, with get and set methods.

that way there will be no difference with working with one customer entry or many.

take a look at this link : http://martinfowler.com/eaaCatalog/dataMapper.html

It is quite a common design pattern for Model-layer classes to have CRUD operations (= create/read/update/delete) that can be performed either on an individual record, or on a set.

In php, you can write methods that check to see whether the parameter that has been passed is either a single value - such as an 'id' - or an array of objects, and then perform the appropriate operation.

function delete($target){
  if (is_array($target)){
    //check that array contains appropriate data, then
    //do a loop through it, deleting every record included:
  else {
    //$target is a single entry, so check that
    // it is an 'id', then delete the appropriate record:

[eluser]Jon L[/eluser]
mihailt, thanks for the tip regarding Data Mapper. it led me to find this project:

PHP Data Mapper is similar to the Ruby Data Mapper implementation, and looks like it's off to a good start.

Teks, my model already has CRUD, I just wasn't sure if it was "best practice" to develop in the method you just suggested. Thanks for your post though, that makes me a bit more confident in that strategy :-)

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.