感谢您的阅读,并考虑我的问题..PHP PDO扶养注射
我是新来的PDO和OOP(正确的方式 - 我一直在使用的对象更像是现在一段时间的功能),以及我试图转换我当前的用户登录脚本,以防止会话劫持(同时使数据库中的数据更容易获取)...无论如何... ...
此外 - 我这样做是为了学习,而不是因为我需要一个登录脚本。如果我需要这样的东西,我会使用已经被证明已经存在的框架。
我构建这个类UserSessions
,这样定义:
class UserSession {
public $userSessionId;
public $loggedInUserId;
public $userIp;
public $userFwdIp;
public $httpUserAgent;
public $authenticated;
private $hashedPassword;
private $suppliedUserName;
private $suppliedPassword;
public function __construct ($pdoConn) {
$this->setUserSessionId();
$this->setUserIp();
$this->setUserFwdIp();
$this->setSessionExpire();
$this->setHttpUserAgent();
$this->setLoggedInUserId();
$this->updateCurrentSession();
}
private function setLoggedInUserId() {
$query = 'select 1 from dual';
$this->loggedInUserId = $pdoConn->query($query)->fetch()[0];
}
// several other methods below that all function properly
}
我这里实例化类:
$databaseConnect = new $config['database_type']($config);
$pdoConn = new PDO( $databaseConnect->connectString
, $databaseConnect->getDataBaseUser()
, $databaseConnect->getDataBasePass()
, array(PDO::ATTR_EMULATE_PREPARES=>false
, pdo::ATTR_ERRMODE=>pdo::ERRMODE_EXCEPTION)
);
$httpReqUser = new UserSession($pdoConn);
不过,我得到以下错误: 调用一个成员函数查询()null
所以,这告诉我,$pdoConn
对象是null
(我想想)...但我不明白为什么。
我已经尝试了新的变量设置为是在通过从构造的外供本地使用这样的$pdoConn
值:
$this->setPdoConn($pdoConn) // and within that method it's a simple setter...
也许我误解究竟我应该在这里做。
基本上 - 这个UserSession
类将需要更新或插入一个表中的几个字段,但它将需要访问PDO,但我不想每次我想要调用一个'新的PDO'在我的所有课程中使用它。 我应该如何解决这个问题?
你可能想看看'依赖注入container'如; http://php-di.org/或http://pimple.sensiolabs.org/ – Perspective
我想知道setLoggedInUserId方法是否是一个真实的 –
@tadman请见第三段。 ... @你的常识,没有那个查询只返回1,但它只返回1,如果连接是好的。 – Jeff