在php中使用抽象类满足接口
我想在我的应用程序中使用Amazon SNS发送文本消息。我唯一担心的是,如果我决定将亚马逊SNS换成其他提供商,会发生什么 我提出了以下解决方案,但不确定这是否是最佳做法,或者这是否会对未来产生任何影响在php中使用抽象类满足接口,php,class,interface,abstract,Php,Class,Interface,Abstract,我想在我的应用程序中使用Amazon SNS发送文本消息。我唯一担心的是,如果我决定将亚马逊SNS换成其他提供商,会发生什么 我提出了以下解决方案,但不确定这是否是最佳做法,或者这是否会对未来产生任何影响 <?php interface SMS { public function sendSMS($from, $to); } abstract class AmazonSNS { public function sendSMS($from, $to) {
<?php
interface SMS {
public function sendSMS($from, $to);
}
abstract class AmazonSNS {
public function sendSMS($from, $to) {
echo 'Message sent';
}
}
class Notification extends AmazonSNS implements SMS {
}
$notification = new Notification;
$notification->sendSMS('xxxx', 'xxxx');
对我来说,最好使用
<?php
interface Notification {
public function notify($from, $to);
}
class AmazonSNSSmsNotification implements Notification {
public function notify($from, $to) {
//send notification using SMS
}
}
class OtherProviderSmsNotification implements Notification {
public function notify($from, $to) {
//send notification using SMS from other provider
}
}
class EmailNotification implements Notification {
public function notify($from, $to) {
//send notification using email
}
}
因为Notification
是接口,所以作为第一个参数传递的实例必须是Notification
接口的实例,否则它将抛出错误。
function sendNotification(Notification $notifObj, $from, $to) {
$notifObj.notify($from, $to);
}
sendNotification(new AmazonSNSSmsNotification(), $from, $to);
sendNotification(new OtherProviderSmsNotification(), $from, $to);