将mysql连接移出另一个类 [英] Move out mysql connection into another class

查看:59
本文介绍了将mysql连接移出另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to move database connective outside this class. So that there is only 1 connection per execution. Also any improvements to the below code is welcome.

<?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设计模式. 此处是一个示例数据库连接单例.

You should look into the Singleton Design Pattern. Here's an example of a database connection singleton.

这篇关于将mysql连接移出另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆