构建自己的PHP框架--实现Model类(1)
在之前的博客中,我们定义了ORM的接口,以及决定了使用PDO去实现。最后我们提到会有一个Model类实现ModelInterface接口。
现在我们来实现这个接口,如下:
<?php
namespace sf\db;
use PDO;
/**
* Model is the base class for data models.
* @author Harry Sun <sunguangjun@126.com>
*/
class Model implements ModelInterface
{
/**
* Declares the name of the database table associated with this Model class.
* @return string the table name
*/
public static function tableName()
{
return get_called_class();
}
/**
* Returns the primary key **name(s)** for this Model class.
* @return string[] the primary key name(s) for this Model class.
*/
public static function primaryKey()
{
return ['id'];
}
/**
* Returns a single model instance by a primary key or an array of column values.
*
* ```php
* // find the first customer whose age is 30 and whose status is 1
* $customer = Customer::findOne(['age' => 30, 'status' => 1]);
* ```
*
* @param mixed $condition a set of column values
* @return static|null Model instance matching the condition, or null if nothing matches.
*/
public static function findOne($condition)
{
}
/**
* Returns a list of models that match the specified primary key value(s) or a set of column values.
*
* ```php
* // find customers whose age is 30 and whose status is 1
* $customers = Customer::findAll(['age' => 30, 'status' => 1]);
* ```
*
* @param mixed $condition a set of column values
* @return array an array of Model instance, or an empty array if nothing matches.
*/
public static function findAll($condition)
{
}
/**
* Updates models using the provided attribute values and conditions.
* For example, to change the status to be 2 for all customers whose status is 1:
*
* ~~~
* Customer::updateAll(['status' => 1], ['status' => '2']);
* ~~~
*
* @param array $attributes attribute values (name-value pairs) to be saved for the model.
* @param array $condition the condition that matches the models that should get updated.
* An empty condition will match all models.
* @return integer the number of rows updated
*/
public static function updateAll($condition, $attributes)
{
}
/**
* Deletes models using the provided conditions.
* WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
*
* For example, to delete all customers whose status is 3:
*
* ~~~
* Customer::deleteAll([status = 3]);
* ~~~
*
* @param array $condition the condition that matches the models that should get deleted.
* An empty condition will match all models.
* @return integer the number of rows deleted
*/
public static function deleteAll($condition)
{
}
/**
* Inserts the model into the database using the attribute values of this record.
*
* Usage example:
*
* ```php
* $customer = new Customer;
* $customer->name = $name;
* $customer->email = $email;
* $customer->insert();
* ```
*
* @return boolean whether the model is inserted successfully.
*/
public function insert()
{
}
/**
* Saves the changes to this model into the database.
*
* Usage example:
*
* ```php
* $customer = Customer::findOne(['id' => $id]);
* $customer->name = $name;
* $customer->email = $email;
* $customer->update();
* ```
*
* @return integer|boolean the number of rows affected.
* Note that it is possible that the number of rows affected is 0, even though the
* update execution is successful.
*/
public function update()
{
}
/**
* Deletes the model from the database.
*
* @return integer|boolean the number of rows deleted.
* Note that it is possible that the number of rows deleted is 0, even though the deletion execution is successful.
*/
public function delete()
{
}
}
当然现在里面还没有写任何的实现,只是继承了ModelInterface接口。
现在我们先来实现一下findOne方法,在开始实现之前我们要想,我们所有的model都要基于PDO,所以我们应该在model中有一个PDO的实例。所以我们需要在Model类中添加如下变量和方法。
/**
* @var $pdo PDO instance
*/
public static $pdo;
/**
* Get pdo instance
* @return PDO
*/
public static function getDb()
{
if (empty(static::$pdo)) {
$host = 'localhost';
$database = 'sf';
$username = 'jun';
$password = 'jun';
static::$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);
static::$pdo->exec("set names 'utf8'");
}
return static::$pdo;
}
用static变量可以保证所有继承该Model的类用的都是同一个PDO实例,getDb方法实现了单例模式(其中的配置暂时hard在这里,在之后的博客里会抽出来),保证了一个请求中,使用getDb只会取到一个PDO实例。
下面我们来实现findOne方法,我们现在定义的findOne有很多局限,例如不支持or,不支持select部分字段,不支持表关联等等。我们之后会慢慢完善这一些内容。其实findOne的实现就是拼接sql语句去执行,直接来看下代码:
public static function findOne($condition)
{
// 拼接默认的前半段sql语句
$sql = 'select * from ' . static::tableName() . ' where ';
// 取出condition中value作为参数
$params = array_values($condition);
$keys = [];
foreach ($condition as $key => $value) {
array_push($keys, "$key = ?");
}
// 拼接sql完成
$sql .= implode(' and ', $keys);
$stmt = static::getDb()->prepare($sql);
$rs = $stmt->execute($params);
if ($rs) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!empty($row)) {
// 创建相应model的实例
$model = new static();
foreach ($row as $rowKey => $rowValue) {
// 给model的属性赋值
$model->$rowKey = $rowValue;
}
return $model;
}
}
// 默认返回null
return null;
}
我们需要来验证一下我们的代码是正确的,先在MySQL中设置一下用户及权限,mock一下数据。
相应的SQL语句如下:
/*创建新用户*/
CREATE USER jun@localhost IDENTIFIED BY 'jun';
/*用户授权 授权jun用户拥有sf数据库的所有权限*/
GRANT ALL PRIVILEGES ON sf.* TO jun@'%' IDENTIFIED BY 'jun';
/*刷新授权*/
FLUSH PRIVILEGES;
/*创建数据库*/
CREATE DATABASE IF NOT EXISTS `sf`;
/*选择数据库*/
USE `sf`;
/*创建表*/
CREATE TABLE IF NOT EXISTS `user` (
id INT(20) NOT NULL AUTO_INCREMENT,
name VARCHAR(50),
age INT(11),
PRIMARY KEY(id)
);
/*插入测试数据*/
INSERT INTO `user` (name, age) VALUES('harry', 20), ('tony', 23), ('tom', 24);
然后再在models文件夹中创建一个User.php,代码如下:
<?php
namespace app\models;
use sf\db\Model;
/**
* User model
* @property integer $id
* @property string $name
* @property integer $age
*/
class User extends Model
{
public static function tableName()
{
return 'user';
}
}
最后只剩在Controller中使用findOne验证一下了。修改SiteController.php的actionTest方法如下:
public function actionTest()
{
$user = User::findOne(['age' => 20, 'name' => 'harry']);
$data = [
'first' => 'awesome-php-zh_CN',
'second' => 'simple-framework',
'user' => $user
];
echo $this->toJson($data);
}
打出的如下结果:
{"first":"awesome-php-zh_CN","second":"simple-framework","user":{"id":"1","name":"harry","age":"20"}}
如果将findOne中的条件改成['age' => 20, 'name' => 'tom'],返回值就变为如下结果:
{"first":"awesome-php-zh_CN","second":"simple-framework","user":null}
好了,今天就先到这里。项目内容和博客内容也都会放到Github上,欢迎大家提建议。
code:https://github.com/CraryPrimitiveMan/simple-framework/tree/0.5
blog project:https://github.com/CraryPrimitiveMan/create-your-own-php-framework
构建自己的PHP框架--实现Model类(1)的更多相关文章
- 构建自己的PHP框架--实现Model类(3)
在之前的博客中,我们实现并完善了Model类的findOne方法,下面我们来实现其中的其他方法. 先来看findAll方法,这个方法和findOne很相似. public static functio ...
- 构建自己的PHP框架--实现Model类(2)
在上一篇博客中我们简单实现了findOne方法,但我们可以看到,还是有一些问题的,下面我们来修正一下这些问题. 首先是返回的数据中,数字被转换成了字符串.我们需要的是数字啊... PDO中有属性可以支 ...
- tp框架之Model类与命名空间
1.获取系统常量信息 public function shuchu() { var_dump(get_defined_constants()); } 2.跨控制器或跨模块调用 function dia ...
- 为测试框架model类自动生成xml结果集
问题:有大量类似于theProductId这样名字的字符串需要转换成the_product_id这种数据库column名的形式. 思路:见到(见)大写字母(缝)就插入(插)一个“_”字符(针)进去,最 ...
- J2EE进阶(七)利用SSH框架根据数据表建立model类
J2EE进阶(七)利用SSH框架根据数据表建立model类 前言 在利用SSH框架进行项目开发时,若将数据库已经建好,并且数据表之间的依赖关系已经确定,可以利用Hibernate的反转功能进行mode ...
- laravel5.1框架model类查询实现
laravel框架model类查询实现: User::where(['uid'=8])->get(); User类继承自Model类:Illuminate\Database\Eloquent\M ...
- yii框架之gii创建数据表相应的model类
一.首先是在数据库中建立project须要的表: 二.然后,配置相应文件: 在project文件夹下yiiProject\protected\config\main.php.在50行定义了db应用组件 ...
- 如何构建Android MVVM 应用框架
概述 说到Android MVVM,相信大家都会想到Google 2015年推出的DataBinding框架.然而两者的概念是不一样的,不能混为一谈.MVVM是一种架构模式,而DataBinding是 ...
- 构建自己的PHP框架--创建组件的机制
在之前的博客中,我们完成了基本的Model类,但是大家应该还记得,我们创建数据库的pdo实例时,是hard好的配置,并且直接hard在Model类中. 代码如下: public static func ...
随机推荐
- js中几种常用的输出方式
1.alert("要输出的内容"); ->在浏览器中弹出一个对话框,然后把要输出的内容展示出来 ->alert都是把要输出的内容首先转换为字符串然后在输出的 2.doc ...
- js中的navigator对象
Navigator 对象包含有关浏览器的信息.所有浏览器都支持该对象 在控制台中输出相关信息的代码 <script> console.log(navigator); </script ...
- mysql多字段排序
在对数据库进行查询的时候有时候需要将查询的结果按照某字段升序或者降序排列,甚至有时候需要按照某两个字段进行升降序排列.如果按照某一字段进行排列,只需要在查询语句最后写上 "order by ...
- [转]定位占用oracle数据库cpu过高的sql
今天在吃饭的时候我的朋友的数据库出现了问题,cpu占用率为97%,当我看到这个问题的时候我就想到了或许是sql导致的此问题,由于忍不住吃饭,暂时没有帮他看这个问题,这是我饭后自己模拟的故障,进行的分析 ...
- C#时间戳转换
,,)).ToUniversalTime ().Ticks ) / ;//先取得当前的UTC时间,然后转换成计算用的周期数(简称计时周期数),每个周期为100纳钞(ns)=0.1微秒(us)=0.00 ...
- eclipse 中的注释 快捷键
(1)Ctrl+Space 说明:内容助理.提供对方法,变量,参数,javadoc等得提示, 应运在多种场合,总之需要提示的时候可先按此快捷键. 注:避免输入法的切换设置与此设置冲突 (2)Ctrl ...
- select 相关
获取select :获取select 选中的 text : ? 1 $("#ddlregtype").find("option:selected").text( ...
- Spring MVC中Session的正确用法<转>
Spring MVC是个非常优秀的框架,其优秀之处继承自Spring本身依赖注入(Dependency Injection)的强大的模块化和可配置性,其设计处处透露着易用性.可复用性与易集成性.优良的 ...
- 多线程中使用CheckForIllegalCrossThreadCalls = false访问窗口-转
在多线程程序中,新创建的线程不能访问UI线程创建的窗口控件,如果需要访问窗口中的控件,可以在窗口构造函数中将CheckForIllegalCrossThreadCalls设置为 false publi ...
- ABP理论学习之验证DTO
返回总目录 本篇目录 验证介绍 使用数据注解 自定义验证 标准化 验证介绍 首先应该验证应用的输入.用户或者其它应用都可以向该应用发送输入.在一个web应用中,验证通常要实现两次:在客户端和服务器端. ...