萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

MongoDB PHP 類庫設計:Table 類獲取 MongoCursor 游標兩種模式

架構概覽

  • Config.php:單例管理 MongoDB 連線、資料庫選擇。
  • Table.php:抽象基類,封裝 CRUD,提供兩種查詢模式回傳游標或資料陣列。

Config.php (連線管理)

<?php
require_once 'Zend/Exception.php';
class Hrs_Mongo_Config {
    const DEFAULT_HOST = 'localhost';
    const DEFAULT_PORT = 27017;
    private static $host = self::DEFAULT_HOST;
    private static $port = self::DEFAULT_PORT;
    private static $options = ['connect' => true, 'timeout' => 30];
    public static $conn = null;
    public static $defaultDb = null;
    public static $linkStatus = '';

    public static function set($server = 'mongodb://localhost:27017', $options = []) {
        // ... 解析 $server 字串或陣列,建立 MongoClient (舊版 Mongo)
        // 現代請用 new MongoDB\Client($uri, $options)
    }
    public static function selectDB($database) { /* ... */ }
}
?>

Table.php 抽象基類

<?php
require_once 'Hrs/Mongo/Config.php';

abstract class Hrs_Mongo_Table {
    protected $_db = '';
    protected $_name = '';      // collection 名稱
    protected $_data = [];      // find() 存放結果陣列
    protected $c_options = ['fsync'=>true, 'safe'=>true];
    protected $u_options = ['multiple'=>true, 'fsync'=>true, 'safe'=>true];
    protected $d_options = ['fsync'=>true, 'justOne'=>false, 'safe'=>true];

    protected function _setAdapter($database) {
        if (!$database) throw new Zend_Exception('DB name required');
        Hrs_Mongo_Config::selectDB($database);
    }

    public function __construct() {
        if (Hrs_Mongo_Config::$conn instanceof Mongo) { // 舊版 Mongo 類別
            $this->_db = Hrs_Mongo_Config::$defaultDb->{$this->_name};
        } else {
            throw new Zend_Exception('MongoDB 連線失敗');
        }
    }

    // --- 基本 CRUD ---
    public function insert($data) { /* ... */ }
    public function update($data, $where) { /* ... */ }
    public function delete($where) { /* ... */ }
    public function dropMe() { /* ... */ }

    // --- 模式一:find() 回傳 $this (鏈式),結果存 $_data ---
    public function find($where = [], $limit = 0) {
        if (!$this->testLink()) return $this;
        $cursor = $where ? $this->_db->find($where) : $this->_db->find();
        if ($limit > 0) $cursor->limit($limit);
        $this->_data = iterator_to_array($cursor); // 將游標轉陣列
        return $this; // 支援 $table->find(...)->toArray()
    }

    public function toArray() {
        $tmp = [];
        foreach ($this->_data as $id => $row) {
            $row['_id'] = $id;
            $tmp[] = $row;
        }
        return $tmp;
    }

    // --- 模式二:look() 直接回傳 MongoCursor 物件 ---
    public function look($where = [], $fields = []) {
        if (!$this->testLink()) return false;
        if ($fields) {
            return $where 
                ? $this->_db->find($where, $fields)
                : $this->_db->find()->fields($fields);
        }
        return $where ? $this->_db->find($where) : $this->_db->find();
    }

    // 替代方案:find() 回傳游標,另提供 getCursor()
    /*
    public function find($where = [], $fields = []) {
        if ($this->testLink()) {
            $this->_data = $this->_db->find($where, $fields)->sort(['_id' => -1]);
        }
        return $this;
    }
    public function getCursor() { return $this->_data; } // 實際為 MongoCursor
    */

    protected function testLink() {
        return Hrs_Mongo_Config::$linkStatus === 'success';
    }
}
?>

使用範例

<?php
class UserTable extends Hrs_Mongo_Table {
    protected $_name = 'users';
}

$userTable = new UserTable();

// 模式一:取得陣列
$users = $userTable->find(['status' => 1], 10)->toArray();

// 模式二:取得游標 (可進一步 limit/skip/sort)
$cursor = $userTable->look(['role' => 'admin']);
$cursor->limit(5)->sort(['created_at' => -1]);
foreach ($cursor as $doc) { /* ... */ }
?>

現代化遷移 (MongoDB PHP Library 1.x+)

  • 使用 MongoDB\Client、MongoDB\Collection。
  • find() 直接回傳 MongoDB\Driver\Cursor (可迭代)。
  • 不再需要自建 Table 基類,直接操作 Collection 物件。
copyright © 萬盛學電腦網 all rights reserved