依赖注入
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;
}
}