Tea*_*App 1 php model codeigniter
最近我开始使用Codeigniter
框架来开发RESTFul
移动应用程序的Web服务.
当我在网站和youtube上查看各种教程时,我发现a的概念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;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
但是,在通过互联网搜索好的教程时,我发现人们只是使用可以访问数据库的数据并将其返回的数据Controller
.
我没有看到任何人在Model中编写普通类(如果你是Java人员,我们称之为POJO)
现在,我在阅读和观看这些教程后所要求的是,
在PHP应用程序框架的上下文中,Model类是数据库的连接器,它在查询时返回与应用程序相关的数据.用SQL语言我们称之为,
CRUD功能
在基于Codeigniter的框架创建的Web应用程序中,MVC模式用于设计应用程序.Model类是具有将应用程序连接到数据库并返回数据的函数,并且有助于在应用程序的数据库上执行所有CRUD操作.
好吧,如果您使用过C#或Ruby,那么您可以找到应用MVC模式的好方法.在PHP中,在我看来,人们有时会对这些术语感到困惑.我在PHP中使用MVC模式的方式如下:
CONTROLLER
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
}
}
Run Code Online (Sandbox Code Playgroud)
模型
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
}
}
Run Code Online (Sandbox Code Playgroud)