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条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用