0

I have a MySQL table that stores people and companies. They have same fields. In php I have

class User{
var $_id;
var $_data;
function loadDataFromDb()
{
}
}

class Company extends User
{
    function getName()
    {
    //some implemantation
    }
}


class People extends User
{
function getName()
{
//some implemantation
}
}

What is the best way of creating the objects. When I creat my object I am not aware of which type of client is.

I need something like:

$user = /* code missing */
$user->getName(); // this will trigger the appropiate method.`
2
  • 1
    How can a company extend a user??
    – PeeHaa
    Feb 8, 2012 at 17:58
  • The problem is that I can decide which type of user is after I load the data from the MySQL. Also I want to have this data as private data of the objects. There won't be User() objects. Only Company or People. User is a generic name for a parent of People and also Company. You could say Client().
    – catalinux
    Feb 8, 2012 at 18:27

3 Answers 3

1

I think a factory method will be suitable for the present case as this factory will give you the object you are looking for.
You have to pass some kind of information though to let factory decide which object should be returned.

2
  • I'd say the info about object type is stored in the DB somehow, so the 2 given fields are likely not the only fields of the table and factory method can read this.
    – Stan
    Feb 8, 2012 at 18:07
  • The problem is that I can decide which type of user is after I load the data from the MySQL. Also I want to have this data as private data of the objects. There won't be User() objects. Only Company or People
    – catalinux
    Feb 8, 2012 at 18:26
1

Abstract Factory pattern:

interface AbstractUserFactory{
   public function buildUser($type);
}

class UserFactory implements AbstractUserFactory {
    public function buildUser($type='user'){
       if($type == 'user'){
          return new User();
       } else if ($type == 'company') {
          return new Company();
       } else if($type == 'people' ) {
          return new People();
       } else{
          throw new Exception("Unknown User type [$type]");
       }
    }

}
0

How about you use an ORM like Doctrine for this sort of work. It supports inheritance so you could map this to you database schema (this should be concrete inheritance class strategy in Doctrine).

Otherwise, try to clarify what is your goal and concrete problem here.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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