سؤال

I have a class User and a class UserFactory (factory pattern). The factory connects to SQL and creates instances of the user object.

Since we often have to preprocess fields retrieved from the database, I'm wondering which is the best place to do so. For example (simplified):

class UserFactory {
    function getUserByID($id) {
        $q = $this->DB->query("SELECT id, name, email FROM user WHERE id = ?", $id);

        if(!$q)
            return FALSE;

        return new User($q);
    }
}

class User {
    function __construct($obj) {
        if(!empty($obj->id))    $this->ID    = (int) $obj->id;
        if(!empty($obj->name))  $this->name  = $obj->name;
        if(!empty($obj->email)) $this->email = $this->verifyEmail($obj->email);
    }
}

In this example the User object does the actual processing, but I dislike how I'm still forced to use the actual SQL field names in the User object while I have this UserFactory designed to be a layer between SQL and PHP.

So I could move the processing to the UserFactory like so:

class UserFactory {
    function getUserByID($id) {
        $q = $this->DB->query("SELECT id, name, email FROM user WHERE id = ?", $id);

        if(!$q)
            return FALSE;

        $user = new User($q->id);
        $user->setName($q->name);
        $user->setEmail($q->email);

        return $user;
    }
}

class User {
    function __construct($id) {
        $this->ID = (int) $id;
    }

    function setName($name) {
        $this->name = $name;
    }

    function setEmail($email) {
        $this->email = $this->verifyEmail($email);
    }
}

I guess this would be a good way to do things, except now I'm making additional function calls for each property which seems unnecessary, and I have to set a list of properties manually with each UserFactory function I create.

Where would I ideally process these fields and assign them to the object? What is the 'accepted way'? Would I create a setter for each property, or add multiple arguments to the User class constructor... I'd like to hear your ideas.

(I know these 'ideal code style' questions can be subjective and hope I'm not breaking any community guidelines with this.)

هل كانت مفيدة؟

المحلول

The UserFactory is not really a Factory class but a Data Mapper.

So your second example is right because the domain model should not know anything about the database. You could also combine it with a Table Data Gateway.

More on this subject: http://richard.jp.leguen.ca/not-blog/why-use-table-data-gateways/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top