vendredi 30 octobre 2015

Understanding design patterns and struggling to write code for it

I'm trying to understand design patterns and I want to implement the best way into my project. I have been reading about it last two days and I understand that singleton pattern is not good unless you want to use it for database. And I wrote the bellow code which is I believe factory pattern. But I don't understand why do I need to use interface? Is there anything wrong with my code? Could you give me any example? My goal is that I want send mail without writing settings for phpmailer every time I need to send mail. Or for any other library I use.

Thanks.

this is my folder structure..

-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);

Aucun commentaire:

Enregistrer un commentaire