Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a class inside another one in PHP

Tags:

oop

php

Hope you can help me with this one: i have two classes: Database and Users. The Database connects to the database using PDO (inside the constructor) and has functions to alter tables, insert data, etc. The Users class will handle login, as well add/remove users. However, the Users class needs to connect to the database. How can i do this?

like image 403
Vinny Avatar asked Dec 07 '22 01:12

Vinny


2 Answers

There are several things you could do:

Globals

$db = new Database();

class Users
{
  public function foo()
  {
    global $db;
    $db->query();
  }
}

Setting a static variable

$db = new Database();

class Model
{
  static public $db;
}

Model::$db = $db;

class Users extends Model
{
  public function foo()
  {
    self::$db->query();
  }
}

Use a singleton

class Database
{
   private static $instance;

   private function __construct()
   {
   }

   public static function instance()
   {
      return self::$instance ? self::$instance : self::$instance = new self();
   }
}

class Users
{
   public function foo()
   {
      Database::instance()->query();
      // or $db = Database::instance(); $db->query();
   }
}

The one thing you want to avoid is creating a new database connection per model or class.

like image 180
Matthew Avatar answered Jan 01 '23 07:01

Matthew


Same way you normally would, but it might help to make the database a class property:

<?php
class Users
{

    protected $_db;

    public function __construct(Database $database = null)
    {
        if (!$database) {
            $database = new Database;
        }
        $this->_db = $database;
    }

    public function addUser($username)
    {
        // Do stuff ...
        $this->_db->insert($data);
    }

}

Then you can use the User class like:

<?php
$users = new Users;
$users->addUser('joebob');
like image 42
Ryan Chouinard Avatar answered Jan 01 '23 08:01

Ryan Chouinard