工厂模式-PHP代码篇

文件结构

DesignPattern
├── Drivers
│   ├── Db_Adapter.php
│   ├── MySQL.php
│   └── sqlite.php
├── index.php
└── sqlFactory.php

先定义一个接口

./Drivers/Db_Adapter.php
规定一些通用方法

<?php

interface Db_Adapter
{
    public function connect($config);
}

定义了MySQL数据库的操作类

./Drivers/MySQL.php
这是一个实现了Db_Adapter接口的类。

<?php

include_once "Db_Adapter.php";

class Db_Adapter_MySQL implements Db_Adapter
{
    private $_dbLink;

    function __construct() {}

    public function connect($config)
    {
        $this->_dbLink = @new mysqli($config['host'], $config["user"], $config["password"], $config["database"], $config['port']);
        if ($this->_dbLink->connect_errno) {
            echo "Failed to connect to MySQL: (" . $this->_dbLink->connect_errno . ") " . $this->_dbLink->connect_error;
        }
        return $this->_dbLink;
    }
}

定义了SQLite数据库的操作类

./Drivers/sqlite.php
这是一个实现了Db_Adapter接口的类。

<?php

include_once "Db_Adapter.php";

class Db_Adapter_sqlite extends SQLite3 implements Db_Adapter
{
    private $_dbLink;

    function __construct() {}

    public function connect($config)
    {
        try {
            if ($this->_dblink = new SQLite3($config['database'] . '.db')) {
                return $this->_dblink;
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

定义工厂类

sqlFactory.php
现在我们需要一个数据库操作的方法,只需要定义一个工厂类,根据传入不同的参数生成不同的类即可。

<?php

class sqlFactory
{
    public static function factory($type)
    {
        if (include_once "Drivers/" . $type . ".php") {
            $classname = 'Db_Adapter_' . $type;
            return new $classname;
        } else {
            throw new Exception ('Driver not found');
        }
    }
}

工厂类如何使用

index.php
调用时,这么写就可以了。

<?php

include_once "sqlFactory.php";

$mysqlConfig = [
    'host' => '10.160.5.28',
    'port' => '3306',
    'user' => 'root',
    'password' => '123456!@#',
    'database' => 'test',
    'charset' => 'utf8mb4',
];

$sqliteConfig = [
    'database' => 'mySQLite',
];
$db = sqlFactory::factory('MySQL');
$connect = $db->connect($mysqlConfig);

$db = sqlFactory::factory('sqlite');
$connect = $db->connect($sqliteConfig);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值