将来的版本会破坏它吗?
是的,因为您使用的是旧的和(现在)已弃用的mysql_*
功能。
类的代码片段lnemail_fetch
这个名字lnemail
对于一个类来说并不是一个好名字,因为当我看到它时,我不知道它是什么ln
意思。类名也经常是UpperCamelCased
和方法camelCased
。
现在实际查看您的代码:
在查看您的课程时,它只是一个课程,目前与 OOP 无关。我会做的是将$result
属性设为私有,因为目前您只是一些数据容器。此外,我将介绍另一个负责从数据库(或您拥有的任何存储)访问数据的类。我还将介绍另一个类来表示单个电子邮件和一个工厂类来构建这些邮件对象。这将类似于以下内容:
// 不确定收件箱的名称是否正确,因为我不太清楚这个类代表什么
class Inbox
{
private $storage;
private $mailFactory;
public function __construct($storage, $mailFactory)
{
$this->storage = $storage;
$this->mailFactory = $mailFactory;
}
public function fetchAllMails()
{
$mailRecordset = $this->storage->fetchAll();
$mails = array();
foreach ($mailRecordset as $mailRecord) {
$mails[] = $this->mailFactory->create($mailRecord);
}
return $mails;
}
}
class InboxStorage
{
private $dbConnection;
public function __construct(\PDO $dbConnection)
{
$this->dbConnection = $dbConnection;
}
public function fetchAll()
{
$stmt = $this->dbConnection->query('SELECT * FROM lnemail');
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
}
class Email
{
private $email;
private $date;
private $week;
public function __construct($email, $date, $week)
{
$this->email = $email;
$this->date = $date;
$this->week = $week;
}
public function getEmail()
{
return $this->email;
}
public function getDate()
{
return $this->date;
}
public function getWeek()
{
return $this->week;
}
}
class EmailFactory
{
public function create($record)
{
return new Email($record['email'], $record['date'], $record['week']);
}
}
你可以像下面这样运行它:
// initialize all the objects we are going to need
$emailFactory = new EmailFactory();
$dbConnection = new \PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$inboxStorage = new InboxStorage($dbConnection);
$inbox = new Inbox($inboxStorage, $mailFactory);
// run the code
foreach($inbox->fetchAllMails() as $email) {
echo $mail->email . ' | ' . $mail->date . ' | ' . $mail->week . '<br>';
}