2014-01-30 20 views
3

我是新設計模式。我有一個登錄系統,有類連接到我的數據庫和類似的東西。如何在PHP登錄系統中使用Observer模式?

但現在我想在我的PHP代碼中包含觀察者模式。但我不知道該怎麼做。例如,每當有新用戶時,我都會通知用戶。我知道觀察者模式是如何工作的,例如它是如何工作的。但我不知道如何將它包含到PHP代碼中。那麼你如何做一個包含觀察者模式的登錄系統呢?

例如這裏是我的連接類到我的數據庫:

private $pdo; 

function __construct() { 
    $this->pdo = new PDO('mysql:host=localhost;dbname=users', '', ''); 
} 

而且繼承人是在登錄文件中使用我的代碼:

if(isset($_POST['username']) && isset($_POST['password'])) { 
    include_once("classes/database.php"); 
    $db = new DB(); 
    $result = $db->query("SELECT username, pass FROM users WHERE username='".$_POST['username']."' AND pass='".$_POST['password']."'"); 

    if(isset($result[0]['username']) && isset($result[0]['password'])) { 
     $_SESSION['username'] = $_POST['username']; 
     header("Location: start.php?username=".$_SESSION['username']); 
    } 
+1

您是否看到developerWorks網站上的示例實現? http://www.ibm.com/developerworks/library/os-php-designptrns/#N10115 – danielpsc

回答

3

這是使用觀察者模式的例子將觀察員註冊到您的登錄系統。在這個例子中,我註冊了一個發送電子郵件時,一個新的用戶創建的管理員觀察員:

首先,我們創建定義的可觀察/觀察員的行爲

interface IObserver 
{ 
    //an observer has to implement a function, that will be called when the observable changes 
    //the function receive data (in this case the user name) and also the observable object (since the observer could be observing more than on system) 
    function onUserAdded($observable, $data); 
} 

interface IObservable 
{ 
    //we can attach observers to the observable 
    function attach($observer); 
} 

然後接口,你讓你的主登錄系統實現IObservable,實現附加功能,並保留一系列觀察者。在內部,你實現了一個通知函數,當它被調用時,迭代數組並通知每個觀察者。

你做什麼,畢竟是創建用戶的正常行爲,你可以調用你的notify函數。

class LoginSystem implements IObservable 
{ 
    private $observers = array(); 

    private function notify($userName) 
    { 
     foreach($this->observers as $o) 
      $o->onUserAdded($this, $userName); 
    } 

    public function attach($observer) 
    { 
     $this->observers []= $observer; 
    } 

    public function createUser($userName) 
    { 

     //all your logic to add it to the databse or whatever, and then: 

     $this->notify($userName); 

    } 

} 

然後,你創建一個類比實現Iobserver。在onUserAdded函數中,當發生觀察事件時,您可以做任何想要發生的事情。在這個例子中,我只是發送郵件給硬編碼的電子郵件。它可以像你想要的那樣複雜。

class NewUserMailer implements IObserver 
{ 
    public function onUserAdded($observable, $data) 
    { 
     mail("[email protected]", "new user", $data); 
    } 
} 

然後,行爲是正義的,創建loginsystem後,你還可以創建一個觀察者,並附加是對登錄系統

$ls = new LoginSystem(); 
$ls->attach(new NewUserMailer()); 

有了這個,每次一個新用戶創建,一個郵件將發送到「[email protected]