Properly calling the database from Model in an MVC application?

前端 未结 4 2067
有刺的猬
有刺的猬 2020-12-01 04:07

I\'m building a tiny MVC framework for learning/experimenting and small project purposes. I needed to find out the basics of the internals of the Model since a full MVC fram

4条回答
  •  猫巷女王i
    2020-12-01 04:33

    In my experience different frameworks interpret MVC somewhat loosely and usually with some deviations. However they usually agree that MVC is divided like this:

    • Model - Business Logic + Data storage / retrieaval / structuring
    • View - Presentation of data
    • Controller - Calling methods on model after analyzing request

    I use Symfony a lot and can give you a couple of small examples. Mind you, these are hugely simplified. :p

    The Model:

    class MyUnitTable extends Doctrine_Table
    {
        // .. various other pieces of code added by Symfony ... //
        public function getForAccount( Account $_account ) {
        $q = $this
             ->createQuery('e')
             ->leftJoin('e.User u')
             ->leftJoin('u.Profile p')
             ->leftJoin('p.Account a')
             ->where('a.accountid = ?', $_account->getAccountid());
        return $q->execute();
        }
    }
    
    class myUnitActions extends sfActions
    {
        public function executeIndex(sfWebRequest $request)
        {
            $this->units = Doctrine_Core::getTable('MyUnit')->getForAccount($foo);
        }
    }
    

    The View (just showing a snippet here):

    • getName(); ?>

    The Controller:

    The controller is the place where a request gets handled. It will analyze the request and figure out which action (eg. myUnitActions::executeIndex() from above) in a model that should be called.

    Last notes:

    I'm sure you can see whats happening in the code above (a lot of convenience is added by the ORM). You have the controller dispatching a request to the model, the model operating withing your problem-domain plus actually pulling data from a database and lastly the view displaying the data.

    This has many benefits to you as a developer as it allows for easier and more reliable testing, among other things.

    An excellend read for you would be the 21 Days With Jobeet guide from the people behind Symfony. It's a nice piece of work.

    You should also have a look at the code for both Symfony and Zend. They are both excellend. Also have a look at a couple of ORM's like Doctrine and Propel.

    Also see the Wikipedia article on MVC.

提交回复
热议问题