stUrb
stUrb

Reputation: 6832

use an object previously declared in an other class

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?

Upvotes: 2

Views: 193

Answers (2)

None
None

Reputation: 5649

There are 2 ways that you could go about this.

The first way, injection, is growing in popularity. Injection means you would supply $db to your class. You could do something like this.

Injection:

class CMS_class {
  protected static $db;

  public function __construct($db) {
    if ( ! isset(self::$db))
      self::$db = $db;
  }

  public function __get($name) {
    if ($name === 'db')
      return self::$db;
  }
}

Now when you construct the CMS class you pass it the $db variable which is accessible via ->db, but there is only one instance.

The second method would be to call it globally in every function you use it.

Global:

class CMS_class {
  function hello_world() {
    global $db;
    var_dump($db);
  }
}

This way is losing popularity because globals are generally frowned upon and you will have to declare it in every function that you need $db.

There are other good answers out there that relate to your question. How can I use "Dependency Injection" in simple php functions, and should I bother?

Upvotes: 1

Halcyon
Halcyon

Reputation: 57719

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.

Upvotes: 3

Related Questions