构建自己的php框架

在之前的博客中,我们实现并完善了model类的findone方法,下面我们来实现其中的其他方法。

先来看findall方法,这个方法和findone很相似。

publicstaticfunction findone($condition = null)
{
$sql = ‘select * from ‘ . static::tablename();$params = [];// 判空if(!empty($condition)) {
$sql .= ‘ where ‘;$params = array_values($condition);$keys = [];foreach($conditionas$key => $value) {
array_push($keys,”$key = ?”);
}
$sql .= implode(‘ and ‘,$keys);
}
$stmt = static::getdb()->prepare($sql);$rs = $stmt->execute($params);$models = [];if($rs) {
// 直接获取出所有符合条件的$rows = $stmt->fetchall(pdo::fetch_assoc);foreach($rowsas$row) {
if(!empty($row)) {
$model = newstatic();foreach($rowas$rowkey => $rowvalue) {
$model->$rowkey = $rowvalue;
}
array_push($models,$model);
}
}
}
returnnull;
}

你会发现有findone和findall方法很相似,明显可以将公共的部分抽出来,然后我们就多了如下两个方法:

/** * build a sql where part * @parammixed $condition a set of column values * @return string */publicstaticfunction buildwhere($condition,$params = null)
{
if(is_null($params)) {
$params = [];
}
$where = ”;if(!empty($condition)) {
$where .= ‘ where ‘;$keys = [];foreach($conditionas$key => $value) {
array_push($keys,”$key = ?”);array_push($params,$value);
}
$where .= implode(‘ and ‘,$keys);
}
return[$where,$params];
}
/** * convert array to model * @parammixed $row the row data from database */publicstaticfunction arr2model($row)
{
$model = newstatic();foreach($rowas$rowkey => $rowvalue) {
$model->$rowkey = $rowvalue;
}
return$model;
}

分别是构建sql中where部分的方法和将查找到的array转换成model的方法。大家会奇怪第一个方法中为什么需要params参数和返回值,其实这个为了之后的updateall方法的使用。其实这个地方跟适合使用引用传值。

这样我们的findone和findall就便成了如下内容:

/** * 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]); * ” * * @parammixed $condition a set of column values * @return static|null model instance matching the condition, or null if nothing matches. */publicstaticfunction findone($condition = null)
{
list($where,$params) = static::buildwhere($condition);$sql = ‘select * from ‘ . static::tablename() . $where;$stmt = static::getdb()->prepare($sql);$rs = $stmt->execute($params);if($rs) {
$row = $stmt->fetch(pdo::fetch_assoc);if(!empty($row)) {
returnstatic::arr2model($row);
}
}
returnnull;
}
/** * 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]); * ” * * @parammixed $condition a set of column values * @return array an array of model instance, or an empty array if nothing matches. */publicstaticfunction findall($condition = null)
{
list($where,$params) = static::buildwhere($condition);$sql = ‘select * from ‘ . static::tablename() . $where;$stmt = static::getdb()->prepare($sql);$rs = $stmt->execute($params);$models = [];if($rs) {
$rows = $stmt->fetchall(pdo::fetch_assoc);foreach($rowsas$row) {
if(!empty($row)) {
$model = static::arr2model($row);array_push($models,$model);
}
}
}
return$models;
}

剩下的updateall/deleteall/insert/update和delete方法就不一一详细说明了,直接给出代码。其基本思想都是一致的,都是按照规则拼接sql语句。

/** * 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’]); * ~~~ * * @paramarray $attributes attribute values (name-value pairs) to be saved for the model. * @paramarray $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 */publicstaticfunction updateall($condition,$attributes)
{
$sql = ‘update ‘ . static::tablename();$params = [];if(!empty($attributes)) {
$sql .= ‘ set ‘;$params = array_values($attributes);$keys = [];foreach($attributesas$key => $value) {
array_push($keys,”$key = ?”);
}
$sql .= implode(‘ , ‘,$keys);
}
list($where,$params) = static::buildwhere($condition,$params);$sql .= $where;$stmt = static::getdb()->prepare($sql);$execresult = $stmt->execute($params);if($execresult) {
// 获取更新的行数$execresult = $stmt->rowcount();
}
return$execresult;
}
/** * 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]); * ~~~ * * @paramarray $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 */publicstaticfunction deleteall($condition)
{
list($where,$params) = static::buildwhere($condition);$sql = ‘delete from ‘ . static::tablename() . $where;$stmt = static::getdb()->prepare($sql);$execresult = $stmt->execute($params);if($execresult) {
// 获取删除的行数$execresult = $stmt->rowcount();
}
return$execresult;
}
/** * 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. */publicfunction insert()
{
$sql = ‘insert into ‘ . static::tablename();$params = [];$keys = [];foreach($thisas$key => $value) {
array_push($keys,$key);array_push($params,$value);
}
// 构建由?组成的数组,其个数与参数相等数相同$holders = array_fill(0,count($keys),’?’);$sql .= ‘ (‘ . implode(‘ , ‘,$keys) . ‘) values ( ‘ . implode(‘ , ‘,$holders) . ‘)’;$stmt = static::getdb()->prepare($sql);$execresult = $stmt->execute($params);// 将一些自增值赋回model中$primarykeys = static::primarykey();foreach($primarykeysas$name) {
// get the primary key$lastid = static::getdb()->lastinsertid($name);$this->$name = (int)$lastid;
}
return$execresult;
}
/** * 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. */publicfunction update()
{
$primarykeys = static::primarykey();$condition = [];foreach($primarykeysas$name) {
$condition[$name] = isset($this->$name)?$this->$name:null;
}
$attributes = [];foreach($thisas$key => $value) {
if(!in_array($key,$primarykeys,true)) {
$attributes[$key] = $value;
}
}
returnstatic::updateall($condition,$attributes) !== false;
}
/** * 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. */publicfunction delete()
{
$primarykeys = static::primarykey();$condition = [];foreach($primarykeysas$name) {
$condition[$name] = isset($this->$name)?$this->$name:null;
}
returnstatic::deleteall($condition) !== false;
}

这样基本的model就算是暂时完成了,虽然可能还有很多问题和局限,但暂时先这样了,我们之后有机会会一步一步的去完善。

好了,今天就先到这里。项目内容和博客内容也都会放到github上,欢迎大家提建议。

code:https://github.com/craryprimitiveman/simple-framework/tree/0.7

blog project:https://github.com/craryprimitiveman/create-your-own-php-framework

以上就介绍了构建自己的php框架–实现model类3,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。

Posted in 未分类

发表评论