了解设计模式并努力为其编写代码

时间:2015-10-30 15:04:38

标签: php oop design-patterns

我试图理解设计模式,我想实现项目的最佳方式。我最近两天一直在阅读它,我知道单身模式并不好,除非你想用它来做数据库。我写了波纹管代码,我相信工厂模式。但我不明白为什么我需要使用界面?我的代码有什么问题吗?你能举个例子吗?我的目标是,每次我需要发送邮件时,我都不想为phpmailer写入设置发送邮件。或者我使用的任何其他库。

感谢。

这是我的文件夹结构..

-lib
---Config.php (configuration class)
---Mail.php
-logs
-models
---Users.php
-public (web root)
---index.php (get routers)
-routers
---users.router.php
-templates
---users.html.twig
-vendor
---slim
---phpmailer
.composer.json
config.php

Mail.php

class Mail {
    protected $mail;

    public function __construct(PHPMailer $mail) {
        $this->mail = $mail;
        $this->mail->isHTML(Config::read('mail.isHtml'));
        $this->mail->setFrom(Config::read('mail.fromEmail'), Config::read('mail.fromName'));
    }

    public function sendMail ( $to, $subject, $body, $plainText ) {
        $this->mail->addAddress($to);
        $this->mail->Subject = $subject;
        $this->mail->Body = $body;
        $this->mail->AltBody = $plainText;

        $this->mail->send();
    }
}

user.router.php

$app->get( '/test', function () use ( $app ) {

    $app->log->info("test '/test' route");

    $mail = new PHPMailer();
    $test = new lib\Mail($mail);

    $test->sendMail('test@domain.com', 'Subject', '<html>Hello username</html>', 'Hello username' );


    var_dump($test);
});

的config.php

Config::write('mail.fromEmail', 'no_reply@domain.dev');
Config::write('mail.fromName', 'Domain LTD');
Config::write('mail.isHtml', true);

1 个答案:

答案 0 :(得分:1)

首先:我在代码中看不到任何工厂模式。

<强>第二 使用工厂模式的目的是获取类的实例,而不是完全了解所获得的类的实现。假设你有两个类,A和B`

class MailerHTML {}

class MailerText {}

现在您可以实现一个工厂来决定您要使用哪个邮件程序。

class MailerFactory 
{
   public function getMailer($supportsHTML)
   {
      if ($supportsHTML) {
          return new MailerHTML();
      } else { 
          return new MailerText();
      }
   }
}

现在你可以从MailerFactory获取al Mailer,而不知道将发送什么类型的邮件,但你也不知道你的邮件程序对象有什么方法签名。 要解决此问题,通常会实现邮件程序类的接口,在您的情况下,抽象sendMail方法

interface MailerInterface 
{
    public function sendMail($to, $subject, $body, $plainText);
}

class MailerHTML implements MailerInterface 
{
    public function sendMail($to, $subject, $body, $plainText) { ... }
}

class MailerText implements MailerInterface {}
{
    public function sendMail($to, $subject, $body, $plainText) { ... }
}