/**
*发送邮件服务类
*/
class EmailService{
public function send(){
//todo 发送邮件方法
}
}
//如果任何地方要发邮件我们就复制下面这两行代码
$emailService = new EmailService();
$emailService->send();
使用了laravel服务容器以后:
$this->app->bind('emailService', function ($app) {
return new EmailService();
});
//如果任何地方要发邮件我们就复制下面这两行代码
$emailService = app('emailService');
$emailService->send();
class SupperEamilService{
//创建静态私有的变量保存该类对象
static private $instance;
//防止直接创建对象
private function __construct(){
}
//防止克隆对象
private function __clone(){
}
static public function getInstance(){
//判断$instance是否是Uni的对象
//没有则创建
if (!self::$instance instanceof self) {
self::$instance = new self();
}
return self::$instance;
}
//发送邮件方法
public function send(){
}
}
<?php
interface TrafficTool{
public function go();
}
class Train implements TrafficTool{
public function go(){
echo "train....";
}
}
class Leg implements TrafficTool{
public function go(){
echo "leg..";
}
}
class Traveller{
/**
* @var Leg|null|Train
* 旅行工具
*/
protected $_trafficTool;
public function __construct(TrafficTool $trafficTool){
$this->_trafficTool = $trafficTool;
}
public function visitTibet() {
$this->_trafficTool->go();
}
}
当旅行者要坐火车去旅行通常我们这样写:
<?php
$train = new Train();
$tra = new Traveller($train);
$tra->visitTibet();
<?php
namespace App\Providers;
use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider{
public function register(){
//在服务容器中绑定类
$this->app->bind( 'TrafficTool', 'Train');
$this->app->bind('Traveller', 'Traveller');
}
}