2013-05-01 59 views
-1

我想讓一個變量(一個PDO實例)可用於我的所有控制器。在我的應用程序/核心/ 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); 
    } 
} 

應用/views/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實例(如果我使用print_r($ this-> pdo在login :: connect它顯示'PDO Object()')。我重定向到主控制器$這個 - > PDO不包含PDO實例。

什麼我做錯了什麼?它有沒有事先與我重定向到主控制器?謝謝做。

+0

你的數據庫連接應該由你的模型,而不是你的控制器來處理。 – 2013-05-01 07:58:16

回答

1

首先,您的PDO對象不應該在您的控制器中。

其次,您的問題是「Home」實例從未創建過pdo對象,這不是控制器,重定向或任何其他錯誤,而是一個基本缺陷在面向對象的思考中

class A { 
    public $test; 
} 

class B extends A { 
    function setTest($test) { $this->test = $test; } 
} 

class C extends A 
{ 
} 

$b = new B(); // create instance of B 
$b->setTest("hello"); // set value in INSTANCE of B 
$c = new C(); // create instance of C 
echo $c->test; // get value from instance of C 

這基本上是你在做什麼。您期望在B的實例中設置的值在C的實例中可用。但這不會起作用。你可以在構造函數或init中初始化pdo,但是這會創建很多pdo實例,所以這樣做不好。你可能需要一個單獨的或註冊表,你可以存儲它並讓它隨時可用。

並再次重複。 pdo不應該在控制器中,但在域邏輯(所以你的型號)

相關問題