I followed the tutorial Build a PHP MVC Application and have implemented a database connection. I made a seperate database connection class and I call it in the controller.
It works, but now I have to inject it whenever I call a method from the user model. Is this considered good (dependency injection) or bad (repeating same variable over and over again seems useless)?
I was thinking about moving the db_con method to the user model itself, but then I'd have to include it in every other future model as well, which is repeating code. Perhaps I should inject it in the first controller method:return new $model();
would become return new $model($this->db_con());
? I don't know anymore. So many possibilities, but where would it fit best?
<?php
class Controller
{
private $db_con = false;
public function model($model)
{
require_once '../app/models/' .$model .'.php';
return new $model();
}
public function view($view, $data)
{
require_once '../app/views/' .$view .'.php';
}
public function db_con()
{
if($this->db_con == false)
{
$database = new Database();
$this->db_con = $database->db_con;
}
return $this->db_con;
}
Now, in my register controller I connect to the user model and inject the database connection like this:
<?php
class Register extends Controller
{
protected $user;
public function __construct()
{
$this->user = $this->model('User');
$this->db_con = $this->db_con();
}
public function form()
{
$this->view('register/form', ['notice' => ""]);
}
public function submit()
{
//Lots of if/elses, then I connect:
elseif($this->user->create_user($this->db_con, $_POST['username'], $_POST['password'], $_POST['email'], $_SERVER['REMOTE_ADDR']))
{
$this->view('register/submit', ['notice' => "You have been registered."]);
}
And to be complete, the database connection class itself:
<?php
class Database
{
public $db_con = false;
public function __construct()
{
try
{
$this->db_con = new PDO('mysql:host='. DB_HOST .';dbname=' . DB_NAME .';charset=utf8', DB_USER, DB_PASS);
}
catch (PDOException $e)
{
error_log($e->getMessage(), 0);
}
}
}
?>