我是设计模式的新手。我有一个登录系统,其中包含用于连接到我的数据库的类以及类似的东西。
但现在我想在我的 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']);
}
最佳答案
这是一个使用观察者模式将观察者注册到您的登录系统的示例。在示例中,我注册了一个观察者,它在创建新用户时向管理员发送电子邮件:
首先,我们创建定义可观察对象/观察者行为的接口(interface)
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,实现附加功能,并保留一个观察者数组。在内部,你实现了一个通知函数,当它被调用时,迭代数组并通知每个观察者。
你所做的,毕竟是创建用户的正常行为,你调用你的通知功能。
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("admin@yoursite.com", "new user", $data);
}
}
然后,行为就是,在创建登录系统之后,您还创建一个观察者,并附加到登录系统
$ls = new LoginSystem();
$ls->attach( new NewUserMailer() );
这样,每次创建新用户时,都会向“admin@yoursite.com”发送一封邮件
关于php - 如何在PHP登录系统中使用观察者模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21455944/