开发者

Question about objects and looking for single rows

I am trying to somehow stick to the rules of object oriented programming. So therefore I have created a user class, which 开发者_如何学JAVAdeals with one user. This user is loaded from the db class user.

So now i am creating a userManager class with functions like: findUserIdByEmail.

But what is the correct object oriented way to do this?

Should I build a query from the userManager straight to the db or should i somehow load all user objects an find it in the objects?


I would build something like getUserByEmail($email) which returns the complete object (with or without related objects). In that case you can access the id with $User->id (or, better, build a nice getter for it), but also other attributes without executing an other query to the database. If you start building functions like getUserIdByEmail, you will soon start building a method like getUserNameByEmail, getUserPasswordByEmail, etc. See the problem?


I would implement

getUserByEmail($email)

Which would call the database or any other datastore. Basic example minus escaping/security

public function getUserByEmail($email)
{
    $sql = "SELECT user_name AS username, user_id AS userId FROM User WHERE email_address =   ". $email
    $result = $this->runQuery($sql);
    while($r = $result->getAssoc()){
        $user = $this->createUserModel($r);    
    }
    return $user;
}

public function createUserModel($row)
{
    $user = new Default_Model_User;
    $user->setUsername($row['username']);
    $user->setUserId($row['userId']);

    return $user;
}

The email method would then call a method that creates the object that holds the properties and return it.


I would create a class Users corresponding to the table where you store users in the database. I would also create a simple User class corresponding to the table structure where you store users.

The table Users would have method getSingleByEmail($theEmail) which would return a User object or null if such user does not exist.

class Users
{
    public function getSingleByEmail($theEmail)
    {
        // check that email is valid
        // if not throw exception

        // get data from the database
        // either with bare SQl or with some db wrapper
        if (null !== theResult)
        {
            theResult = new User($theResult);
        }
        return theResult;
    }
}

class User
{
    private $id;
    private email;
    private $username;

    public function __construct($theResult)
    {
        $this->id = theResult->id;
        $this->email = theResult->email;
        $this->username = theResult->username;
    }
}

Or something like that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜