当用户登录我的站点时,我会创建我的User
类的一个实例,获取一些与用户相关的数据并将对象存储在SESSION
.
我从数据库中获取的一些数据应该在整个会话期间保持不变,并且我希望可以从其他对象访问这些数据。在使用另一个对象中的值时,我更喜欢使用User::$static_value_in_class
to $_SESSION['static_value_in_session']
,但我愿意说服。
问题是,当我将User
实例序列化到 中时,这些值不会被记住SESSION
,然后加载不同的页面。
类定义:
class User {
public $name;
public static $allowed_actions;
public function __construct($username, $password) {
// Validate credentials, etc.
self::$allowed_actions = get_allowed_actions_for_this_user($this);
}
}
class Blog {
public static function write($text) {
if (in_array(USER_MAY_WRITE_BLOG, User::$allowed_actions)) {
// Write blog entry
}
}
}
登录.php:
$user = new User($_POST['username'], $_POST['password']);
if (successful_login($user)) {
$_SESSION['user'] = $user;
header('Location: index.php');
}
索引.php:
if (!isset($_SESSION['user'])) {
header('Location: login.php');
}
Blog::write("I'm in index.php! Hooray!")
// Won't work, because Blog requires User::$allowed_actions
我应该实现Serializable
和编写自己的版本serialize()
并unserialize()
包含静态数据吗?
我应该咬紧牙关$_SESSION
从Blog
课堂上访问变量吗?
我是否应该要求将有效User
实例发送到该Blog
write()
方法?
或者,也许互联网有更好的主意......
编辑:编写我的真实用例(不是完整的代码,但足以了解要点)。
我的网站处理具有共享预算帐户的用户组。用户可以将团体的钱花在团体同意的某些事情上,他们通过创建Transaction
类的实例并将其发送到Bank
类进行数据库存储来报告交易。
Bank
班级:
class Bank {
// Group-agreed reasons to spend money
public static $valid_transaction_reasons;
public function __construct(User $user) {
Bank::$valid_transaction_reasons = load_reasons_for_this_group($user->bank_id);
}
}
User
班级:
class User {
public $bank_id;
public function __construct($username, $password) {
$query = "SELECT bank_id FROM users WHERE username=$username AND password=$password";
$result = mysql_fetch_array(mysql_query($query));
$this->bank_id = $result['bank_id'];
}
}
Transaction
班级:
class Transaction {
public function __construct($reason, $amount) {
if (!in_array($reason, Bank::$valid_transaction_reasons)) {
// Error! Users can't spend money on this, the group doesn't cover it
}
else {
// Build a Transaction object
}
}
}
实际代码(login.php 之类的):
$user = new User($_GET['uname'], $_GET['pword']);
$_SESSION['bank'] = new Bank($user);
// Some shit happens, user navigates to submit_transaction.php
$trans = new Transaction(REASON_BEER, 5.65);
// Error! Bank::$valid_transaction_reasons is empty!