如何在业务逻辑中使用接口

时间:2013-09-27 06:04:30

标签: php design-patterns interface

如何在业务逻辑中使用接口?例如,如果我有这样的网关接口,如下所示:

<?php
    interface Gateway()
    {
        function writeToDatabase();
        function readFromDatabase();
    }
?>

并为特定数据库实施它:

<?php
    class MySQL implements Gateway
    {
       public function writeToDatabase()
       {
          //Write data to database here....
       }

       public function readFromDatabase()
       {
          //Read data from database here...
       }
   }
?>

如何在不对MySQL类进行特定引用的情况下在业务逻辑中使用网关接口?我可以在类构造函数中键入提示接口,如下所示:

<?php
    class BusinessClass
    {
        private $gateway;

        public function __construct(Gateway $gateway)
        {
           $this->gateway = $gateway;
        }
    }
 ?>

但是我还没有找到一种方法来实例化一个使用Gateway接口的新对象而不说:

$gateway = new MySQL();

我宁愿不这样做,因为如果我决定为另一个数据库编写另一个Gateway接口实现,我将不得不将业务逻辑中的所有硬引用从“MySQL”更改为新的实现。这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用Abstract Factory Pattern。对于这种模式,您只需在代码的一个点配置一次具体工厂,而不再仅仅。

如果您认为是过度设计,因为您的应用程序非常简单,只需执行以下操作:

Public class GatewayFactory{

Public static IGateWay CreateGateway(){

//read app configuration file, constant or whatever you use to configure gatewaytype in design time or runtime
string gateWayType = readGatewayTypeCofiguration();
if (gateWayType = Constants.MySQL) {return New MySQL()}//Use Constants! Don't hardcode literal Strings
if (gateWayType = Constants.SQLServer) {return New SQLServer()}
//etc...

  }
}

当GateWay更改时,只需更改配置,其他所有内容都保持不变。

相关问题