我正在尝试使我的所有控制器都可以使用一个变量(一个 PDO 实例)。在我的 application/core/MY_Controller.php 我有:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
public $pdo;
}
应用程序/控制器/login.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MY_Controller
{
public function index()
{
if(!$this->pdo instanceof PDO)
{
$this->load->view('login_form');
}
else
{
redirect('home');
}
}
public function connect()
{
$hostname = $this->input->post('hostname');
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->pdo = new PDO("mysql:host=$hostname", $username, $password);
if($this->pdo instanceof PDO)
{
redirect('home');
}
else
{
$this->index();
}
}
}
应用程序/控制器/home.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends MY_Controller
{
public function index()
{
echo 'PDO should be available here but it is not:';
print_r($this->pdo);
}
}
应用程序/视图/login_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login form</title>
</head>
<body>
<div>
<?php echo form_open('login/connect'); ?>
<label for="hostname">Hostname</label>
<input type="text" id="hostname" name="hostname" />
<label for="username">User name</label>
<input type="text" id="username" name="username" />
<label for="password">Password</label>
<input type="text" id="password" name="password" />
<input type="submit" id="submit" name="submit" />
<?php echo form_close(); ?>
</div>
</body>
我正在本地测试这个。当我转到站点地址时,登录表单按预期显示。在提交时 login::connect() 被调用并且我知道 $this->pdo 包含一个 PDO 实例(如果我在 login::connect 中使用 print_r($this->pdo 它显示'PDO Object ()')。但是当我重定向到 Home 控制器 $this->pdo 不包含 PDO 实例。
我究竟做错了什么?它与我重定向到 Home 控制器有关吗?提前致谢。