Simple Model
class Database {
   protected $_conn;
   public function __construct($connection) {
       $this->_conn = $connection;
   }
   public function ExecuteObject($sql, $data) {
       // stuff
   }
}
abstract class Model {
   protected $_db;
   public function __construct(Database $db) {
       $this->_db = $db;
   }
}
class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}
$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');


Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.


You can have the data access in the model itself (the MVC pattern doesn't restrict you from doing that), but it's easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):


修改时间 2016-08-28

真诚赞赏,手留余香
赞赏
随机推荐
CommonJS和AMD
JS中(function(){xxx})(); 这种写法是什么意思?
Webpack的项目中,如何import导入绝对路径
CentOS 8 使用防火墙限制每个 IP 的最大连接数
RESTful API 设计指南
Node.js 异步异常处理
express不是内部或外部命令,也不是可运行的程序或批处理文件
display:inline-block元素之间空隙的产生原因和解决办法
Content Security Policy 与跨域脚本攻击 XSS
Javascript去字符串前后空格5种实现方法及比较