I am trying to get a database instance via any model-class that uses the database.
This is ideal in my opinion:
class UserAuthenticator
{
private $db;
private $customer;
public function __construct(Database $db, Customer $customer)
{
$this->db = $db;
$this->customer = $customer;
}
}
Using a dependency injection.
But my team refuse to use dependency injections.
Which of the 2 options should be better and why?
Option 1: Just getting the instance of the database directly only in models that need the database.
class UserAuthenticator
{
private $db;
private $customer;
public function __construct()
{
$this->db = Database::getInstance();
$this->customer = Customer::getInstance();
}
}
Option 2: Having a "general" Base class, that will extend all models, forcing them to use the database (which isn't a must in models right?)
namespace MyApp\Models\Base;
use MyApp\Core\Database as db;
class Database {
protected $db;
public function __construct() {
$this->db = db::getInstance();
}
}
use MyApp\Models\Base\Database as Base;
class UserAuthenticator extends Base
{
private $customer;
public function __construct()
{
parent::__construct();
$this->customer = Customer::getInstance();
}
}