Where should I set my db object in my model? (MVC)

I would like to know where is the best place to set my db object with my model.

Do I have to hard-code it since my model needs to be constructed for one project, so I set it inside my constructor or wherever I start the initialization? or Do I have to pass the db object to my constructor when installing my object?

What is the best way, I mean power users, and efficient that will give me more options to use?

+1


a source to share


3 answers


A couple of things:

  • Most PHP projects that use a database connection represent that database with a Singleton pattern , in case you are not sure if this is readable in it.

  • I usually define my database connections in a config file that can be easily changed between environments (development, stage, production).

  • Then I'll create a database connection in the bootstrap file using the above Singleton template and config file.

  • My models tend to completely abstract the database / table datastore, for each model I will do something like this:

bootstrap.php   

$config = load_config_data(ENVIRONMENT);

Db::setDefaultAdapter($config['database']);

      

Model / Table / User.php   



class Table_User extends Db_Table 
{
  // Table name
  protected $_name = 'user';

  /* Do a bunch of database specific stuff */
}

      

Model / User.php

class User extends Model 
{
  public function updateUsername($userid, $username)
  {
    // Uses default adapter, Singleton pattern!
    $table = Db::loadTable('user');
    $table->update(
      array('username'=>$username),
      Db::quoteInto('userid = ?', $userid)
    );
  }
}

      

This is pretty much an introduction to Model in Zend Framework MVC , I would go over some ideas on how to organize your code (or save some hassle and actually use the framework .)

+2


a source


To test, you must pass it to the constructor, not hardcode it. This helps you write a unit test because you can mock your DB object.



+1


a source


I would not hard code it even if the code is never used for another project, just going from test database to live database may need to find and modify the code in the model class. It will be much better placed in some kind of config file.

Personally, I would have a db object defined in what you use as bootstrap - and then the model (s) use that single object.

0


a source







All Articles