开发者

Where to connect to DB in MVC

开发者 https://www.devze.com 2022-12-20 06:40 出处:网络
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

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,开发者_如何学C where should I put the code that connects to the DB and processes it? Would this go in the Model class?


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.


All the database interaction is inside the Model class.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消