什么是“;型号“;在CodeIgniter应用程序的上下文中


What is "model" in context of CodeIgniter application?

最近我开始使用Codeigniter框架,以便为移动应用程序开发RESTFul web服务。

当我在网站和youtube上查看各种教程时,我发现Model的概念在PHP应用程序上下文中的使用方式有所不同。

有什么不同

好吧,正如我一直认为模型类应该是

Cat.php

<?php
class Cat {
   
   // Class variables
   private $colour;
   
   public __construct() {
      $colour = 'Brown';
   }
   // Getters and Setters
   public function getColour() {
      return $this->colour;
   }
   public function setColour($newColour) {
      $this->colour = $newColour;
   }
}
?>

但是,当我在互联网上搜索好的教程时,我发现人们只是使用可以访问数据库获取数据并将其返回到Controller的函数。

我还没有见过任何人在Model中编写普通类(如果你是Java用户,我们称之为POJO


现在,在阅读和观看这些教程后,

在PHP应用程序框架的上下文中,Model类是数据库的连接器,该数据库在查询时返回与应用程序相关的数据。在SQL语言中,我们称之为

  • CRUD功能

    • 创建
    • 读取
    • 更新
    • 删除

所以,如果我错了,请纠正我

在以类Codeigniter框架为基础创建的web应用程序中,使用MVC模式来设计应用程序。Model类将具有将应用程序连接到数据库并返回数据的功能,以及帮助在应用程序的数据库上执行所有CRUD操作的功能。

好吧,如果你使用过C#或Ruby,你可以找到一种应用MVC模式的好方法。在我看来,在PHP中,人们有时会对术语感到困惑。我在PHP中使用MVC模式的方式如下:

控制器

class UserController { 
    private $repo;
    public function __construct() { 
        $this->repo = new UserRepository(); // The file which communicates with the db. 
    }
    // GET
    // user/register
    public function register() { 
        // Retrieve the temporary sessions here. (Look at create function to understand better)
        include $view_path;
    }
    // POST
    // user/create
    public function create() { 
        $user = new User($_POST['user']); // Obviously, escape and validate $_POST;
        if ($user->validate())
            $this->repo->save($user); // Insert into database
        // Then here I create a temporary session and store both the user and errors.
        // Then I redirect to register
    }
}

型号

class User { 
    public $id;
    public $email;
    public function __construct($user = false) {
        if (is_array($user))
            foreach($user as $k => $v) 
                $this->$$k = $v;
    } 
    public function validate() { 
        // Validate your variables here
    }
}