Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to connect to DB in MVC

I am using php and building an MVC for my web application. I am to the step where I need to connect to my DB, look at the current URL, compare that to data in my DB, and then return the correct content from my DB to the user.

My question is, where should I put the code that connects to the DB and processes it? Would this go in the Model class?

like image 417
Nic Hubbard Avatar asked Feb 10 '10 20:02

Nic Hubbard


3 Answers

The model should be the entity that actively uses the database connection, for simple models using a table gateway/active record implementation may work. For more complex models a data mapper further isolates the database from the rest of your application (which makes it less invasive to change a storage back-end).

You controller should process the request and pass whatever relevant data is needed to the model.

That said, simply setting up a database connection is usually done by some kind of bootstrap script. The model (or the data mapper) then uses the connection. I'm not sure if that technically falls under 'controller'. In practice most frameworks have bootstraps, routers, and front controllers - whatever you call them your database should be used by the model but setup by your bootstrap.

like image 58
Tim Lytle Avatar answered Oct 19 '22 21:10

Tim Lytle


All the database interaction is inside the Model class.

like image 25
Anthony Forloney Avatar answered Oct 19 '22 22:10

Anthony Forloney


Well, the model is just the definition of an object, which could be Vehicle for instance. So, the connection to the database, should be in a Model abstract class (which the Vehicle class would inherit), with methods that could save this information.

If you want more flexibility and more advanced stuff that has already been made, use a framework, personally I would recommend CakePHP.

like image 36
jpabluz Avatar answered Oct 19 '22 21:10

jpabluz