php - 将 mysql 连接移出到另一个类中

标签 php mysql pdo

将数据库连接移到此类之外的最佳方法是什么。这样每次执行只有 1 个连接。另外,欢迎对以下代码进行任何改进。

<?php

    $DatabaseConfig = array(
        'username'  =>  'root',
        'password'  =>  'root',
        'host'      =>  'localhost',
        'database'  =>  'live'
    );

    define('APPPATH', '/var/www/');

    require_once APPPATH.'lib/KLogger.php';

    class BaseModel {

/**
 * var $klogger object klogger instance  
 */
        protected $Klogger;

/**
 * var $Mysqli object mysqli instance  
 */
        protected $DBH;

/**
 * function to initiate logger and database
 */         

        function __construct()
        {
            $this->Klogger  = KLogger::instance(APPPATH.'tmp/logs/mysql/', KLogger::INFO);

            $this->initDb();
        }

/**
 * function to initiate database
 */         
        protected function initDb()
        {
            global $DatabaseConfig;


            try{
                $this->DBH = new PDO("mysql:host=".$DatabaseConfig['host'].";dbname=".$DatabaseConfig['database'], 
                                    $DatabaseConfig['username'], $DatabaseConfig['password']);

            }
            catch(PDOException $e){
                 $this->Klogger->logError($e->getMessage());
                 exit;
            };


        }
/**
 * function to initiate database
 */
        protected function fetch($query,$data = array())
        {
            try
            {
                $STH = $this->DBH->prepare($query);
                $STH->execute();

                $result = array();
                while($row = $STH->fetch(PDO::FETCH_ASSOC)) {  
                    $result[] =$row;
                }
                return $result;
            }
            catch(Exception $e){

                 $this->Klogger->logError($e->getMessage().' \n Query : '.$query);
                 return false;
            };

        }
/**
 * function to save to database
 */
        protected function save($query,$data = array())
        {

            try
            {
                if(empty($data))
                {
                     throw new Exception('Data Not Passed To save');
                }
                $STH = $this->DBH->prepare($query);
                $STH->execute($data);
                return true;

            }
            catch(Exception $e){

                 $this->Klogger->logError($e->getMessage().' \n Query : '.$query);
                 return false;
            };

        }
    }
?>


<?php

require_once 'base_model.php';

class profile extends BaseModel
{
    function test()
    {

        $data   = $this->fetch("SELECT * FROM users");

        $result = $this->save("INSERT INTO users (name, age) VALUES (?,?)",array("tow",1)); 

        var_dump($data);

        var_dump($result);

    }
}

$profile = new profile();
$profile->test();
?>

最佳答案

您应该查看 Singleton Design PatternHere's数据库连接单例示例。

关于php - 将 mysql 连接移出到另一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9637782/

相关文章:

php - PDO:未选择数据库

php - 在 PHPDoc 中记录 Controller 操作的好方法?

php - 执行 mysqli_query 时 SQL 语法错误

php - 将 PHP 数据库值直接保存在 session 数组中是否安全?

php - Laravel 5.1 whereNotNull 与 join 不起作用(返回所有数据)

mysql - 嵌套 SQL 查询中的排序依据

php - PDO异常 “could not find driver”

php - 如何使用 php 准备语句在 mysql 中选择日期范围

php - 使用 php 将文件上传到 imgur 并检索链接

php - 调用mysql连接+查询或调用数据文件哪个更快?