How to create an instance of a database object to be used in other classes?

I ran into an architectural problem with my application. I deployed my own (very simple) MVC, and one of my models is a database object:class MySQLDatabase { }

There are several places where I want to use my database object without creating duplicate instances. Inside my controller I declared public $db;and inside __construct { }I have$this->db = new MySQLDatabase;

Question:

How to use $dbin my other classes - they are all created in the controller __construct { }, but ... I would declare global $dbat the top of all my classes that require a database connection?

I use global variables declared in the global scope as regular variables, and then using the keyword globalto refer to the global scope ... I'm not sure if this applies to variables declared in the class (my controller.)

+3
source share
6 answers

I would stay away from using globals or the Singleton pattern (which is essentially global), and try to find alternatives. In addition, you are talking about connecting to a database using the Singleton template, you are saying that there will never be more than one database connection, while this is usually true in small applications, as they grow larger, you won’t be able to host multiple connections.

- , , /. MVC, , , /singleton, . .

, MVC, , ? , - .

, , factory factory.

, , , .

Singleton, :

...

+4

, , .

, .

class ControllerIndex extends Controller
{
    public function index()
    {
        $this->db->selectAll("table");
    }
}

, , .

, , , , ..

class Users_Model extends Model
{
    public function getUser($id)
    {
    }
}

, , ModelLoader.

:

class ModelLoader
{
    private $models = array();

    public function __get($model)
    {
        //load (/application/models/?.php) and initiate it here
        //Storing it in models array above
    }
}

:

class Controller
{
    private $model;

    public function __construct()
    {
        $this->model = new ModelLoader;
    }
}

, :

class Controller_index extends Controller
{
    public function index()
    {
        $user = $this->model->users->getUser(22);
    }
}

, !

+2

, . :)

. http://en.wikipedia.org/wiki/Singleton_pattern

singleton php:

<?php
class UniqueObject {

    private $_uniq = null;

    //private cause you don't want to instanciate the classic way
    private function __construct() {
        //...
    }

    //check if unique object exists or not, then return it
    public static function uniq() {
        if(!self::$_uniq)
            self::$_uniq = new UniqueObject();

        return self::$_uniq;
    }
}

//call your unique object whenever you need it
UniqueObject::uniq();
?>

(late, I hope I was not mistaken :))

+1
source

Do not use singletones. It is much better to explicitly transfer data. For instance:

abstract class Controller {
  private static $conn; // could be an array for multiple connections
  final protected function getDBConnection() {
    if (!$this->conn) {
      $this->conn = new DBConnection();
    }
    return $this->conn;
  }
  abstract public function process(Request $r);
}

class HomePageController extends Controller {

  public function process(Request $r) {
    $results = $this->getDBConnection()->query('SELECT stuff FROM foo;');
    // do stuff with $results
  }

}

You can also have an explicit model object that you pass, for example. one that represents the user, but which may be redundant for your project.

+1
source

You will need a singleton template. They give examples in php docs

<?php
class Example
{
    // Hold an instance of the class
    private static $instance;

    // A private constructor; prevents direct creation of object
    private function __construct() 
    {
        echo 'I am constructed';
    }

    // The singleton method
    public static function singleton() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

    // Example method
    public function bark()
    {
        echo 'Woof!';
    }

    // Prevent users to clone the instance
    public function __clone()
    {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}

?>

http://php.net/manual/en/language.oop5.patterns.php

0
source

Source: https://habr.com/ru/post/1796697/