美文网首页
如何写一个属于自己的数据库封装(12) - 分页篇

如何写一个属于自己的数据库封装(12) - 分页篇

作者: 梅先森森森森森森 | 来源:发表于2019-10-13 14:28 被阅读0次

上一期 如何写一个属于自己的数据库封装(11) - 关联关系篇

本期要点

php实现分页代码

开始之前

添加了一个简单的 URL 类封装, 虽然没什么必要但这样做可以让代码看起来更简洁

Url.php

由于太简单所以自行食用源代码吧, 就不多介绍了

<?php

/**
* URL Generator
*/
class Url {
    private $host, $queries = [];

    public function __construct() {
        $this->host = (isset($_SERVER['HTTPS']) ? "https" : "http")."://$_SERVER[HTTP_HOST]";
        if(!empty($_SERVER['QUERY_STRING'])) {
            foreach (explode('&', $_SERVER['QUERY_STRING']) as $query) {
                $this->queries[explode('=', $query)[0]] = explode('=', $query)[1];
            }
        }

    }

    public function current($withQueries = 1) {
        if($withQueries)
            return $this->host.$_SERVER["REQUEST_URI"];

        return $this->host.preg_replace('/\?.+$/', '', $_SERVER["REQUEST_URI"]);
    }

    public function to($path) {
        return $this->host."/".preg_replace('/^\//','',$path);
    }

    public function getQuery($key = null) {
        if(is_null($key)) return $this->queries;
        if(isset($this->queries[$key])) return $this->queries[$key];
        return false;
    }

    public function setQuery($key, $value) {
        $this->queries[$key] = $value;
        return $this->current(0).$this->generateQueryString();
    }

    public function removeQuery($key) {
        unset($this->queries[$key]);
        return $this->current(0).$this->generateQueryString();
    }

    public function generateQueryString() {
        $string = [];
        foreach($this->queries as $key => $value) {
            $string[] = "$key=$value";
        }
        return "?".implode('&', $string);
    }
}

helper.php

  • url - 再封装成函数, 增强易用性
function url($path = null) {
    if(is_null($path)) return new Url;
    return (new Url)->to($path);
}

Builder.php

  • paginate - 分页返回数据
    // 就这么简单问你怕不怕
    public function paginate($offset = 1, $size = 20) {
    // 抓取限定的数据量(默认20条数据), 再根据页面数来抓取正确的数据
        return $this->take($size)->skip(($offset-1)*$size)->get();
    }

例子

显示所有演员的记录, 并实现分页, 简单搜索名字的功能

<?php
// 毫无疑问, 先载入轮子
require __DIR__.'/lib/autoload.php';

// 代入 Actor 类
$actors = new Actor;

// 检测是否有 _GET 参数, 有的话接入 where 函数
if(isset($_GET['first_name']))
    $actors = $actors->where('first_name', 'like' ,"%".$_GET['first_name']."%");

// 计算总记录数
$total = (clone $actors)->select('count(*) as total')->first()->total;

// 计算每页显示的记录数, 默认为10
$perPage = isset($_GET['perPage']) ? $_GET['perPage'] : 10;

// 调用 paginate 函数, 首參为当前页数, 默认为1, 2參为每页显示的记录数, 默认为10
$actors = $actors->paginate(isset($_GET['page']) ? $_GET['page'] : 1,$perPage);

// 生成页数链
$links = [];

for($i=1; $i<=ceil($total/$perPage); $i++) {
    // 使用了 URL 类封装, 设置新的 $_GET 参数并且生成 url 链接
    $url = url()->setQuery('page', $i);
    // 生成单条页面链接
    $links[] = "<li style='display:inline;margin:5px'><a href='$url'>$i</a></li>";
}
?>

// 显示总记录数
<h1>Actor List (<?php echo $total; ?>)</h1>
<form>
    <label>Search First Name</label>
    <input type="text" name="first_name">
    <button>search</button>
</form>
<table>
    <tr>
        <th>ID</th>
        <th>FIRST NAME</th>
        <th>LAST NAME</th>
    </tr>
    // 循环列出演员详情
    <?php foreach ($actors as $actor) { ?>
    <tr>
        <td><?php echo $actor->actor_id; ?></td>
        <td><?php echo $actor->first_name; ?></td>
        <td><?php echo $actor->last_name; ?></td>
    </tr>
    <?php } ?>
</table>

<ul>
// 显示所有链接
<?php echo implode('', $links);  ?>

</ul>

效果

image

完结有感

好吧果然拖延症发作了......
再加上接了一些小项目赚点零花(金钱才是最大的推动力), 延迟了不少才写完最后这么一点
而且最后两篇感觉写的不是很好, 不过就这样先吧, 如果有人反正不可能反映看不懂我再看怎么改
以上,感谢为我点赞并关注的各位(一鞠躬)

完整代码

源代码放在coding.net里, 自己领

上一期 如何写一个属于自己的数据库封装(11) - 关联关系篇

相关文章

网友评论

      本文标题:如何写一个属于自己的数据库封装(12) - 分页篇

      本文链接:https://www.haomeiwen.com/subject/rwnhmctx.html