doudui1850 2012-04-13 18:13
浏览 32
已采纳

使用先前在其他类中声明的对象

This is my general php page:

<?php
require_once('includes.php');
require_once('cms.class.php');
.....
rest of the page
?>

in includes.php an pro object called $db is initiated which I want to use in the class specified in the cms.class.php

includes.php:

$db = new PDO('mysql:host=localhost;dbname=xxxxx','xxxxx','xxxxxx'); 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

How can I use this database object in my classes without having multiple places where my credentials are stored?

  • 写回答

2条回答 默认 最新

  • dtn51137 2012-04-13 18:35
    关注

    You need want a dependency manager or a bootstrapper or whatever you want to call it.

    class Dependency_Manager {
    
        private $db;
    
        public function __construct($settings) {
            $this->db = new PDO('mysql:host=localhost;dbname=' . settings["dbname"],settings["username"],$setings["password"]); 
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        }
    
        public function getDB() {
            return $db;
        }
    
    }
    
    class CMS {
        public function __construct(PDO $db) {
            /* .. */
        }
    }
    
    $setting = array(/* etc */);
    
    $dm = new Dependency_Manager($settings);
    $cms = new CMS($dm->getDB());
    

    This approach scales very well and can handle any dependecy. It also aims to put all the settings in one place so you don't have configuration settings littered everywhere. The $dm is the only one who knows the settings, if you need to construct something based on the settings, put it in the $dm.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?