如何寫一個屬于自己的數(shù)據(jù)庫封裝(12) - 分頁篇

上一期 如何寫一個屬于自己的數(shù)據(jù)庫封裝(11) - 關(guān)聯(lián)關(guān)系篇

本期要點

php實現(xiàn)分頁代碼

開始之前

添加了一個簡單的 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 - 再封裝成函數(shù), 增強易用性
function url($path = null) {
    if(is_null($path)) return new Url;
    return (new Url)->to($path);
}

Builder.php

  • paginate - 分頁返回數(shù)據(jù)
    // 就這么簡單問你怕不怕
    public function paginate($offset = 1, $size = 20) {
    // 抓取限定的數(shù)據(jù)量(默認20條數(shù)據(jù)), 再根據(jù)頁面數(shù)來抓取正確的數(shù)據(jù)
        return $this->take($size)->skip(($offset-1)*$size)->get();
    }

例子

顯示所有演員的記錄, 并實現(xiàn)分頁, 簡單搜索名字的功能

<?php
// 毫無疑問, 先載入輪子
require __DIR__.'/lib/autoload.php';

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

// 檢測是否有 _GET 參數(shù), 有的話接入 where 函數(shù)
if(isset($_GET['first_name']))
    $actors = $actors->where('first_name', 'like' ,"%".$_GET['first_name']."%");

// 計算總記錄數(shù)
$total = (clone $actors)->select('count(*) as total')->first()->total;

// 計算每頁顯示的記錄數(shù), 默認為10
$perPage = isset($_GET['perPage']) ? $_GET['perPage'] : 10;

// 調(diào)用 paginate 函數(shù), 首參為當前頁數(shù), 默認為1, 2參為每頁顯示的記錄數(shù), 默認為10
$actors = $actors->paginate(isset($_GET['page']) ? $_GET['page'] : 1,$perPage);

// 生成頁數(shù)鏈
$links = [];


for($i=1; $i<=ceil($total/$perPage); $i++) {
    // 使用了 URL 類封裝, 設置新的 $_GET 參數(shù)并且生成 url 鏈接
    $url = url()->setQuery('page', $i);
    // 生成單條頁面鏈接
    $links[] = "<li style='display:inline;margin:5px'><a href='$url'>$i</a></li>";
}
?>

// 顯示總記錄數(shù)
<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>
    // 循環(huán)列出演員詳情
    <?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>

效果

demo.gif

完結(jié)有感

好吧果然拖延癥發(fā)作了......
再加上接了一些小項目賺點零花(金錢才是最大的推動力), 延遲了不少才寫完最后這么一點
而且最后兩篇感覺寫的不是很好, 不過就這樣先吧, 如果有人反正不可能反映看不懂我再看怎么改
以上,感謝為我點贊并關(guān)注的各位(一鞠躬)

完整代碼

源代碼放在coding.net里, 自己領

上一期 如何寫一個屬于自己的數(shù)據(jù)庫封裝(11) - 關(guān)聯(lián)關(guān)系篇

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容