Where do I put a database query in MVC?

前端 未结 5 1416
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 08:41

The last few days, I have extensively read books and web pages about OOP and MVC in PHP, so that I can become a better programmer. I\'ve come upon a little problem in my und

5条回答
  •  失恋的感觉
    2020-12-01 09:21

    To go even further, your model should not contain the database access code. This belongs to another layer outside the Model/View/Controller: this is called the persistence layer, which can be implemented using an Object-Relational Mapper such as the popular Doctrine 2 for PHP.

    This way, you never touch any (my)SQL code. The persistence layer takes care of this for you. I really advise you to have a look at a Doctrine tutorial, this is a really professional way to create your applications.

    Instead of working with raw data loaded from the database, you create objects that hold your data, and the behavior associated with it.

    For example, you might have a User class, such as:

    class User
    {
        protected $id;
        protected $name;
        protected $privileges;
    
        public function setName($name) { ... }
        public function getName() { ... }
    
        public function addPrivilege(Privilege $privilege) { ... }
        public function getPrivileges() { ... }
    }
    

    You controller will only interact with objects:

    class UserController
    {
        public function testAction()
        {
            // ...
    
            $user = $em->getRepository('User')->find(123); // load User with id 123
            $user->setName('John'); // work with your objects,
            echo $user->getName();  // and don't worry about the db!
            $em->flush(); // persist your changes
        }
    }
    

    Behind the scenes, the ORM takes care of all the low-level work of issuing a SELECT query, instantiating your object, detecting modifications to your object, and issuing the necessary UPDATE statement!

提交回复
热议问题