依赖注入实现邮件发布

2017-11-13  本文已影响0人  kevin_cf

依赖注入

1.目录树

/Di
/--comment.php
/--EmailSenderInterface.php
/--Gmail.php
/--index.php
/--Qmail.php

1.index.php
<?php
/**
 * 自动加载类
 */
namespace Di;

class Load
{
    public static function run()
    {
        spl_autoload_register([self::class, 'loadClass'], false, true);
    }

    public static function loadClass($className)
    {
        $prefix = __NAMESPACE__ . '\\';
        $prefixLength = strlen($prefix);

        $file = '';

        if (0 == strpos($className, $prefix)) {
            $file =  explode('\\', substr($className, $prefixLength));
            $file = implode(DIRECTORY_SEPARATOR, $file) . '.php';
        }

        $path = __DIR__ . DIRECTORY_SEPARATOR . $file;
        if (is_file($path)) {
            require_once $path;
        }
    }
}

$load = new Load();
$load::run();

$comment = new Comment(Gmail::getInstance());
// $comment = new Comment(Qmail::getInstance());

var_dump($comment->save());
2.comment.php
<?php
namespace Di;

class Comment
{
    public $mail;
    public function __construct(EmailSenderInterface $mail)
    {
        $this->mail = $mail;
    }

    public function save()
    {
       return $this->mail->sendMail();
    }

}

3.EmailSenderInterface.php
<?php
namespace Di;

interface EmailSenderInterface
{
    public function sendMail();
}
4.Gmail.php
<?php
namespace Di;

class Gmail implements EmailSenderInterface
{
    private static $gmail;

    public function sendMail()
    {
        return '124';
    }

    public static function getInstance()
    {
        if (!self::$gmail instanceof self)
        {
            self::$gmail = new self();
        }
        return self::$gmail;
    }

}
5.Qmail.php
<?php
namespace Di;

class Qmail implements EmailSenderInterface
{
    private static $qqmail;

    public function sendMail()
    {
        echo 'QQmail';
        return 'send QQmail';
    }

    public static function getInstance()
    {
        if (!self::$qqmail instanceof self)
        {
            self::$qqmail = new self();
        }
        return self::$qqmail;
    }

}
上一篇 下一篇

猜你喜欢

热点阅读