0

OOP、SESSIONS 和用户帐户中跟踪用户信息以在整个网站中使用的最佳方式是什么。(例如 Stack Overflow、Facebook、Google、YouTube 等)

我在想,一旦用户登录,您就可以将所有信息分配给会话数组。例如:

$_SESSION['user_id'],$_SESSION['roles']。

然后在 OOP 中你可以这样做:

$foo->getUserId()、$foo->getAge($user_id) 等。

我想我的问题是处理信息以用于基于用户的网页上的动态内容的最佳方法是什么?(例如用户资料、年龄、加入日期等)。我应该只存储 user_id 的 SESSION 变量,然后使用 user_id 来获取我想要的信息吗?

4

2 回答 2

3

使用 OOP 主体的主要优点之一是一切都成为对象,具有自己的属性。

假设您已经处理了登录过程,您最好以某种方式使用他们的 session_id() 作为标识符,查找他们的用户 ID,然后从 User 类返回一个新对象。这是一个示例:

class User
{
    public $forename;
    public $surname;
    public $google;
    ...

    function __construct($id)
    {
        // Get the record from the DB and assign thevalues as follows:
        $this->forename = $dbobject->forename;
        $this->surname = $dbobject->surname;
        $this->google = $dbobject->google;
    }
}

然后您需要创建 User 对象,您可以将其分配为当前登录的用户:

$logged_in = new User($id);

此后,可以使用 访问每个属性$logged_in->forename

于 2012-12-06T15:10:30.743 回答
0

You would want to minimize the data you would store in $_SESSION[].

I'm not sure if you can do classes or structs in PHP, but you probably want to create an object of User that has the properties username, user id, roles (array), at minimum. You may add other information that you know will be displayed on every page. This way, you would only have one item in the $_SESSION[] for the user.

As long as the user is logged in, you always have $_SESSION['User'], and you would probably want to use the user info to determine which data to display (blog entries, posted videos, etc), and which sections of the page to show/hide depending on that user's roles.

于 2012-12-06T15:14:11.443 回答