Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将mysql连接移出到另一个类中_Php_Mysql_Pdo - Fatal编程技术网

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

Php 将mysql连接移出到另一个类中,php,mysql,pdo,Php,Mysql,Pdo,将数据库连接移动到此类之外的最佳方法是什么。因此,每次执行只有1个连接。此外,欢迎对以下代码进行任何改进 <?php $DatabaseConfig = array( 'username' => 'root', 'password' => 'root', 'host' => 'localhost', 'database' => 'live' ); de

将数据库连接移动到此类之外的最佳方法是什么。因此,每次执行只有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();
?>


将数据库内容移出课堂似乎不是一个好的解决方案。尝试使用单例模式:

您应该查看。数据库连接单例的一个示例。

您能解释一下这个代码类数据库{//存储数据库私有静态$m_pInstance的单个实例;私有函数_construct(){…}公共静态函数getInstance(){if(!self::$m_pInstance){self::$m_pInstance=new Database();}返回self:$m_pInstance;}}}简而言之,您得到的是一个只能实例化一次的类。而不是调用构造函数(
$db=new Database()
),而是使用方法
getInstance
,如下所示:
$db=Database::getInstance()
。该方法负责创建一次对象,并在每次调用时返回相同的实例。这样,每次请求时只需连接到DB一次,并使用该连接执行所有查询和操作。我建议您阅读Wikipedia关于Singleton模式的文章,我在回答中链接了该文章。