当用户登录我的网站时,我会创建一个实例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()
and unserialize()
包括静态数据?
我应该咬住嘴唇并进入$_SESSION
来自内部的变量Blog
class?
我是否需要提供有效的User
实例发送到Blog
write()
method?
或者也许互联网有更好的主意......
EDIT:写我的real用例(不是完整的代码,但足以了解要点)。
我的网站处理具有共享预算帐户的用户组。
用户可以将团体资金花在团体同意的某些事情上,并且他们通过创建团体的实例来报告交易Transaction
类并将其发送到Bank
数据库存储类。
Bank
class:
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:
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:
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!