lundi 26 janvier 2015

How to avoid passing Database object to each Model object without having to use global variables?

To avoid global variables or static configuration classes, I'm passing the database object to each and every one of my models when I instantiate them:



$user = new User( App::getDatabase() );
if( !$user->loggedIn() ) doSomething();


App being a class with static members.


This is really cumbersome but the only alternative is to use the static class(or global variable) from within the model classes:



class User extends Model {

function loggedIn() {
$database = App::getDatabase();
$database->query('stuff');
// you get the picture
}
}


But this is just like using global variables.


Another idea would be to pass the database to the parent class from which each model inherits from:



class Model {
protected static $database

public static function setDatabase($database) {
$this->database = $database;
}

// more stuff here
}

class User extends Model {

function loggedIn() {
parent::$database->query('stuff');
// you get the picture
}
}

Model::setDatabase($myDatabase);


However I'm new to PHP and I havent tried this yet.


Is this a good idea? Is there any alternative out there?


Aucun commentaire:

Enregistrer un commentaire