Documentation

On this page

Download full book (text)

# **Chapter 12: Integrating Third-Party Database Models with SartajPHP** > **Prerequisites:** Chapters 1-11 cover basic SartajPHP concepts and Page helper methods > **Try it:** All code in this chapter is tested code from the runnable example > gate `pdodemo` (`apps/examples/PdoDemo.gate.php` + `apps/examples/NoteModel.php`). > Open `http://localhost/SartajPhpDoc/pdodemo-install.html` once, then > `http://localhost/SartajPhpDoc/pdodemo.html`. --- ## **12.1 Why Integrate Third-Party Database Models?** While SartajPHP's built-in `$this->page` helper methods (`viewData`, `insertData`, `updateData`, `deleteRec`) and `$this->dbEngine` work well for all cases, you may also need ORM style: - **Advanced ORM features** - Relationships, migrations, query builders - **Multiple database support** - Connect to different databases simultaneously - **Code reuse** - Use existing Doctrine/Eloquent models in SartajPHP - **Complex queries** - Join builders, aggregations, pagination This chapter shows how a plain **PDO** model class runs beside SartajPHP while the component system keeps working. **These third-party layers can make you slow** — use them only when you actually need their features. ## **12.2 The Three Layers (same table, three doors)** The example table `book2_note` is read and written through three independent paths: ```mermaid flowchart LR subgraph gate [PdoDemo Gate] A[page_new] -->|dbEngine raw SQL| DB[(book2_note)] B[page_submit] -->|page-insertData helper| DB C[page_event_pdoX] -->|NoteModel over PDO| DB end ``` | Layer | Code | Use when | |-------|------|----------| | Framework engine | `$this->dbEngine->executeQuery(...)` | You want framework connection/error handling | | Framework helpers | `$this->page->insertData($form2, $extra)` | HTMLForm-driven CRUD (Ch 4-7) | | Third-party PDO | `new NoteModel($pdo)` | Doctrine/Eloquent/your own class | ## **12.3 The Third-Party Model (plain PDO)** `apps/examples/NoteModel.php` knows nothing about SartajPHP — it receives a standard PHP `PDO` object: ```php <?php // apps/examples/NoteModel.php class NoteModel { /** @var PDO */ private $pdo; public function __construct(PDO $pdo) { $this->pdo = $pdo; } /** @return array all notes, newest first */ public function all() { $stmt = $this->pdo->query( 'SELECT id, txttitle, txabody, update_timestamp FROM book2_note ORDER BY id DESC' ); return $stmt->fetchAll(PDO::FETCH_ASSOC); } /** @return int new record id */ public function create($title, $body) { $stmt = $this->pdo->prepare( 'INSERT INTO book2_note (userid, parentid, txttitle, txabody, submit_timestamp, update_timestamp, spcmpId) VALUES (0, 0, :t, :b, :ts, :ts2, "pdo")' ); $now = (string) time(); $stmt->execute(array(':t' => $title, ':b' => $body, ':ts' => $now, ':ts2' => $now)); return (int) $this->pdo->lastInsertId(); } /** @return int affected rows */ public function update($id, $title, $body) { $stmt = $this->pdo->prepare( 'UPDATE book2_note SET txttitle = :t, txabody = :b, update_timestamp = :ts WHERE id = :id' ); $stmt->execute(array( ':t' => $title, ':b' => $body, ':ts' => (string) time(), ':id' => (int) $id )); return $stmt->rowCount(); } /** @return int affected rows */ public function delete($id) { $stmt = $this->pdo->prepare('DELETE FROM book2_note WHERE id = :id'); $stmt->execute(array(':id' => (int) $id)); return $stmt->rowCount(); } } ``` ## **12.4 Building the PDO Connection in the Gate** The Gate creates a PDO connection to the **same SQLite file** the framework uses (`comp.php`: `$db = PROJ_PATH . "/db/spanel.db";`): ```php <?php // apps/examples/PdoDemo.gate.php require_once(__DIR__ . '/NoteModel.php'); /** * Build a plain PDO connection to the same SQLite file the framework uses. * For MySQL, build instead: * new PDO("mysql:host=$host;dbname=$name;charset=utf8mb4", $user, $pass) */ private function getPdo() { $dbFile = PROJ_PATH . '/db/spanel.db'; $pdo = new PDO('sqlite:' . $dbFile); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } ``` **Naming pitfall (tested):** do NOT name the Gate class `Pdo`. PHP class names are case-insensitive, so `class Pdo extends BasicGate` collides with the built-in `PDO` class. The example uses `PdoDemo` (registered as gate `pdodemo`). ## **12.5 Using the Model in Page Events** ```php <?php // apps/examples/PdoDemo.gate.php /** URL: pdodemo-pdolist.html — list via NoteModel (plain PDO) */ public function page_event_pdolist($evtp) { $model = new NoteModel($this->getPdo()); $html = ''; foreach ($model->all() as $row) { $html .= '<tr><td>' . $row['id'] . '</td><td>' . htmlspecialchars($row['txttitle']) . '</td><td>' . htmlspecialchars((string) $row['txabody']) . '</td></tr>'; } $this->rowsHtml = $html; $this->statusMsg = 'Listed via NoteModel over plain PDO (third-party layer)'; $this->setFrontFile($this->mainFront); } /** URL: pdodemo-pdocreate-TITLE.html — insert via NoteModel */ public function page_event_pdocreate($evtp) { $title = ($evtp !== '') ? str_replace('-', ' ', $evtp) : 'PDO note ' . date('His'); $model = new NoteModel($this->getPdo()); $id = $model->create($title, 'created by NoteModel::create()'); $this->renderNoteList('NoteModel inserted id=' . $id . ' (plain PDO prepared INSERT)'); } /** URL: pdodemo-pdoupdate-ID-NEWTEXT.html — update via NoteModel */ public function page_event_pdoupdate($evtp) { $parts = explode('-', (string) $evtp, 2); if (count($parts) === 2) { $model = new NoteModel($this->getPdo()); $n = $model->update((int) $parts[0], str_replace('-', ' ', $parts[1]), 'updated by NoteModel'); $this->renderNoteList('NoteModel updated ' . $n . ' row(s) id=' . (int) $parts[0]); } else { $this->renderNoteList('Use pdodemo-pdoupdate-ID-NEWTEXT.html'); } } /** URL: pdodemo-pdodelete-5.html — delete via NoteModel */ public function page_event_pdodelete($evtp) { if ($evtp !== '' && $evtp !== null) { $model = new NoteModel($this->getPdo()); $n = $model->delete((int) $evtp); $this->renderNoteList('NoteModel deleted ' . $n . ' row(s) id=' . (int) $evtp); } else { $this->renderNoteList('Use pdodemo-pdodelete-ID.html'); } } ``` ## **12.6 The Framework Layers on the Same Table** For comparison, the same Gate also uses the framework's own doors: ```php <?php // apps/examples/PdoDemo.gate.php /** Shared list renderer (dbEngine raw SQL). $msg = status to show. */ private function renderNoteList($msg) { $db = $this->dbEngine; $db->connect(); $result = $db->executeQuery( 'SELECT id, txttitle, txabody FROM book2_note ORDER BY id DESC' ); $html = ''; while ($row = $db->rowFetchAssoc($result)) { $html .= '<tr><td>' . $row['id'] . '</td><td>' . htmlspecialchars($row['txttitle']) . '</td><td>' . htmlspecialchars((string) $row['txabody']) . '</td></tr>'; } $db->disconnect(); $this->rowsHtml = $html; $this->statusMsg = $msg; $this->setFrontFile($this->mainFront); } /** URL: pdodemo.html (POST) — insert via $this->page->insertData */ public function page_submit() { $form2 = $this->editFront->getComponent('form2'); global $cmpId; $extra = array(); $extra[]['userid'] = 0; $extra[]['parentid'] = 0; $extra[]['spcmpId'] = $cmpId; $extra[]['submit_timestamp'] = time(); $extra[]['update_timestamp'] = time(); $id = $this->page->insertData($form2, $extra); if (!getCheckErr() && $id) { $this->pageName = 'PDO Interop'; $this->renderNoteList('insertData() inserted id=' . $id . ' (framework helper)'); } else { setErr('pdo', 'Insert failed'); $this->setFrontFile($this->editFront); } } ``` Verified flow (all through `http://localhost/SartajPhpDoc/`): 1. `pdodemo-install.html` → creates `book2_note` 2. POST form → `insertData()` → `insertData() inserted id=N (framework helper)` 3. `pdodemo-pdocreate-Note-from-PDO.html` → `NoteModel inserted id=M (plain PDO prepared INSERT)` 4. `pdodemo-pdoupdate-M-Renamed-By-PDO.html` → `NoteModel updated 1 row(s) id=M` 5. `pdodemo-pdolist.html` → PDO model sees the row written by `insertData()` 6. `pdodemo-pdodelete-M.html` → `NoteModel deleted 1 row(s) id=M` Both layers see each other's writes immediately — it is one SQLite file, two doors. ## **12.7 Component-Binding Helpers on a Third-Party Model** A plain PDO model can do everything `Page::insertData/updateData/viewData` do — without touching `SphpBase::dbEngine()` — by walking the form's bound children itself. The walk is the same one the framework helpers do: > every child where `dataBound && !blnDontSubmit` contributes > `dbField => value` to the write; every child with a `dbField` receives a > value on read. `apps/examples/NoteModel.php` (tested): ```php <?php // apps/examples/NoteModel.php — component-binding helpers /** Walk bound children into an assoc array, merge $extra on top. */ private function formToData($form, $extra = array()) { $data = array(); foreach ($form->getAllChildren() as $comp) { if ($comp->dataBound && !$comp->blnDontSubmit) { $data[$comp->dbField] = $comp->value; } } foreach ($extra as $col => $val) { $data[$col] = $val; } return $data; } /** Insert bound form values + $extra. @return int new id */ public function insertForm($form, $extra = array()) { $data = $this->formToData($form, $extra); $cols = array_keys($data); $ph = array(); foreach ($cols as $c) { $ph[] = ':' . $c; } $sql = 'INSERT INTO book2_note (' . implode(',', $cols) . ') VALUES (' . implode(',', $ph) . ')'; $stmt = $this->pdo->prepare($sql); foreach ($data as $c => $v) { $stmt->bindValue(':' . $c, $v); } $stmt->execute(); return (int) $this->pdo->lastInsertId(); } /** Update bound form values + $extra for $id. @return int affected rows */ public function updateForm($form, $id, $extra = array()) { $data = $this->formToData($form, $extra); $sets = array(); foreach (array_keys($data) as $c) { $sets[] = $c . ' = :' . $c; } $sql = 'UPDATE book2_note SET ' . implode(', ', $sets) . ' WHERE id = :__id'; $stmt = $this->pdo->prepare($sql); foreach ($data as $c => $v) { $stmt->bindValue(':' . $c, $v); } $stmt->bindValue(':__id', (int) $id); $stmt->execute(); return $stmt->rowCount(); } /** Fill bound form children from record $id (like Page::viewData). */ public function viewForm($form, $id) { $stmt = $this->pdo->prepare('SELECT * FROM book2_note WHERE id = :id'); $stmt->execute(array(':id' => (int) $id)); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row === false) { return false; } foreach ($form->getAllChildren() as $comp) { if ($comp->dbField != '' && isset($row[$comp->dbField])) { $comp->value = $row[$comp->dbField]; } } // Same as Page::viewData: mark the form as an update so the rendered // form carries the hidden recID and isUpdateRequest() is true on POST. $form->setRecId($id); return true; } ``` **Tested pitfall:** `viewForm` MUST call `$form->setRecId($id)`. Without it the edit form renders no hidden recID, `isUpdateRequest()` is false on POST, and `page_event_savehelp` silently INSERTs a duplicate instead of updating. Gate usage (`pdodemo-helpaddnew.html`, `pdodemo-helpedit-1.html`, POST `pdodemo-savehelp.html`): ```php <?php // apps/examples/PdoDemo.gate.php /** URL: pdodemo-helpedit-5.html — fill form via NoteModel::viewForm */ public function page_event_helpedit($evtp) { $form2 = $this->helpFront->getComponent('form2'); $model = new NoteModel($this->getPdo()); if ($model->viewForm($form2, $evtp)) { $this->pageName = 'Edit Note id=' . (int) $evtp . ' (NoteModel::viewForm)'; $this->setFrontFile($this->helpFront); } else { $this->renderNoteList('No note with id=' . (int) $evtp); } } /** URL: pdodemo-savehelp.html (POST) — insert/update via NoteModel */ public function page_event_savehelp($evtp) { $form2 = $this->helpFront->getComponent('form2'); $model = new NoteModel($this->getPdo()); $extra = array( 'userid' => 0, 'parentid' => 0, 'spcmpId' => 'help', 'update_timestamp' => time(), ); if ($form2->isUpdateRequest()) { $n = $model->updateForm($form2, $form2->getRecId(), $extra); $this->renderNoteList('NoteModel::updateForm updated ' . $n . ' row(s) id=' . $form2->getRecId()); } else { $extra['submit_timestamp'] = time(); $id = $model->insertForm($form2, $extra); $this->renderNoteList('NoteModel::insertForm inserted id=' . $id); } } ``` Verified: `pdodemo-savehelp.html` POST → `NoteModel::insertForm inserted id=9`; edit flow → `NoteModel::updateForm updated 1 row(s) id=1`. ## **12.8 How the Page Helpers Work Internally** Knowing the internals explains both patterns above. Each helper walks the form and then talks to `\SphpBase::dbEngine()` — nothing else: | Helper | Component filter | Engine calls it makes | |--------|------------------|----------------------| | `insertData($form, $extra)` | `dataBound && !blnDontSubmit && !blnDontUpdate` | `connect()` → `insertSql($frm, $tbl)` → `executeQuery($sql)` → `lastInsertId()` → `disconnect()` | | `updateData($form, $extra, $recID, $where)` | `dataBound && !blnDontSubmit && !blnDontUpdate` | `connect()` → `updateSql($frm, $tbl, $where)` → `executeQuery($sql)` → `disconnect()` | | `viewData($form, $recID, $fldList, $where)` | `dbField != '' && !blnDontFill` | `connect()` → `executeQuery("SELECT $fldList FROM $tbl $where")` → `rowFetchAssoc($result)` → fills `$comp->value` (casts BOOLEAN) → `$form->setRecID($recID)` | | `deleteRec($recid)` | — (uses Gate `tblName`) | `connect()` → `executeQuery("DELETE FROM $tbl WHERE id='$recid'")` → `disconnect()` | Details that matter: - Field name comes from `dfield` (`$comp->dbField`); table from `dtable` (`$comp->dbTable`), falling back to the Gate's `setTableName()` value. - `$extra` accepts both shapes: `$extra[]['userid'] = 0;` (flat) or `$extra['book2_note']['userid'] = 0;` (per-table). - `updateData` with empty `$recID` uses `$form->getRecID()` and builds `WHERE id='...'` — which is why the edit form must carry the recID. - Because the helpers only need `insertSql / updateSql / executeQuery / rowFetchAssoc / lastInsertId / connect / disconnect`, **any object providing those methods can serve as the engine** — that is the next section. ## **12.9 Writing a Drop-in dbEngine Object (the MySqliPdo pattern)** The framework ships its engines as classes extending `\Sphp\Kit\DbEngine`: `Sphp\Lib\MySql`, `Sphp\Lib\Sqlite`, `Sphp\Lib\MySqliPdo`, `Sphp\Lib\PostgresSqlPdo`. `MySqliPdo` is the reference PDO adapter: ```php <?php namespace Sphp\Lib { class MySqliPdo extends \Sphp\Kit\DbEngine { public static $dlink; // shared PDO link public static $isConnect = false; public $allQueryOk = true; private $engine = null; public $sphpApi = null; private $settings = null; private $pdo = null; private $transactionDepth = 0; // Constructor receives the Engine wrapper — same for every engine public function __construct($engine) { $this->engine = $engine; $this->sphpApi = $engine->getSphpApi(); $this->settings = $engine->getSettings(); } public function connectServer($dbHost1, $dbUser1, $dbPass1) { // new \PDO("mysql:host=$host;port=$port", $user, $pass) // ERRMODE_EXCEPTION, store in static $dlink, $isConnect = true } public function connect($db1 = "", $dbHost1 = "", $dbUser1 = "", $dbPass1 = "") { // fill blanks from $this->settings (comp.php values), // connectServer() once, then selectDb($db1) } // cleanQuery via $pdo->quote() minus surrounding quotes // executeQuery / executeQueryQuick via $pdo->query($sql) // insertSql / updateSql / searchSql build SQL strings, cleanQuery values // rowFetchAssoc / rowFetchArray via $result->fetch(PDO::FETCH_ASSOC|BOTH) // lastInsertId via $pdo->lastInsertId() // transactions: disableAutoCommit/commit/rollback with $transactionDepth } } ``` The **rule** (this is what makes engines interchangeable): > A new dbEngine object must behave exactly like the built-in engines inside > the Gate class — `$this->dbEngine->connect()`, `executeQuery()`, > `rowFetchAssoc()`, and the Page helpers must all work **with zero changes to > any Gate code**. Changing database engine = changing one line in `comp.php`. `apps/examples/engines/SqlitePdoEngine.php` in this project is that exercise: the same class shape as `MySqliPdo`, but `new \PDO('sqlite:' . $dbFile)` instead of MySQL. It extends `\Sphp\Kit\DbEngine` and overrides the MySQL-specific parent methods: ```php <?php namespace Sphp\Lib { class SqlitePdoEngine extends \Sphp\Kit\DbEngine { public static $dlink; public static $isConnect = false; public $allQueryOk = true; private $settings = null; private $pdo = null; private $transactionDepth = 0; public function __construct($engine) { $this->sphpApi = $engine->getSphpApi(); $this->settings = $engine->getSettings(); } public function connectServer($dbFile = '') { // new \PDO('sqlite:' . $file), ERRMODE_EXCEPTION, static $dlink } public function connect($db1 = "", $dbHost1 = "", $dbUser1 = "", $dbPass1 = "") { // SQLite needs only the file: settings->db (comp.php $db) if (!SqlitePdoEngine::$isConnect) { $this->connectServer($db1 !== '' ? $db1 : $this->dbFile()); } } public function executeQuery($sql) { // Auto-connect like MySqliPdo — Pagination calls this // without connect() first. if (!SqlitePdoEngine::$isConnect) { $this->connect(); } // return $this->pdo->query($sql) with setErr on failure } public function insertSql($frm, $txttbl) { /* like MySqliPdo */ } public function updateSql($frm, $txttbl, $where) { /* like MySqliPdo */ } public function rowFetchAssoc($result) { return $result->fetch(\PDO::FETCH_ASSOC); } public function lastInsertId() { return $this->pdo->lastInsertId(); } // SQLite overrides of MySQL-specific parent helpers: public function getDbTables() { /* sqlite_master instead of SHOW TABLES */ } public function getTableColumns($t) { /* PRAGMA table_info */ } public function isRows($result) { /* $result->rowCount(), not mysqli_num_rows */ } public function emptyTable($t) { /* DELETE FROM, SQLite has no TRUNCATE */ } } } ``` **Contract checklist** (what the framework actually calls — implement all of these; the parent `DbEngine` gives you `fetchQuery`, cache helpers, and `getTableSql` for free as long as your `executeQuery`/`rowFetchAssoc`/ `insertSql`/`updateSql` work): | Group | Methods | |-------|---------| | Connection | `connect`, `connectServer`, `disconnect`, `getDatabaseLink`, `__destruct` | | Escaping | `cleanQuery`, `clearQuery` | | Execution | `executeQuery`, `executeQueryQuick`, `exec`, `prepare`, `multiQuery` | | SQL builders | `insertSql`, `insertSqlMulti`, `updateSql`, `searchSql`, `runSql`, `runUpdateSql` | | Results | `rowFetchAssoc`, `rowFetchArray`, `lastInsertId`, `isRecordExist`, `isRows` | | Transactions | `disableAutoCommit`, `enableAutoCommit`, `commit`, `rollback`, `commitRollback` | | Tables (optional) | `getDbTables`, `getTableColumns`, `createTable`, `dropTable`, `emptyTable` | **Tested pitfalls found while making the swap transparent:** 1. **`executeQuery` must auto-connect.** `Pagination` runs its `SELECT count()` through `executeQuery()` without calling `connect()` first. A strict engine fails with `Call to a member function query() on null`. 2. **Do NOT override `fetchQuery` with a flat array.** The parent returns `array("news" => array(key => row))` and `Pagination` reads `$data["news"]` — a flat array gives `Undefined array key "news"`. Inherit the parent implementation; it works through your `executeQueryQuick` + `rowFetchAssoc`. 3. **`executeQueryQuick` should not disconnect mid-request** for PDO engines: rows stream from the live connection, so `rowFetchAssoc()` after a disconnect fails. Keep the static link alive; `__destruct` closes it. ## **12.10 Swapping Engines — Zero Gate Changes** Because `SqlitePdoEngine` satisfies the contract, the whole project can run on it by changing **one line** in `comp.php`: ```php // built-in SQLite3 engine $dbEnginePath = $libPath . "/Sphp/Lib/Sqlite.php,Sphp\Lib\Sqlite"; // built-in MySQL PDO engine $dbEnginePath = $libPath . "/Sphp/Lib/MySqliPdo.php,\\Sphp\\Lib\\MySqliPdo"; // our custom PDO engine (file path + class, comma separated) $dbEnginePath = __DIR__ . "/apps/examples/engines/SqlitePdoEngine.php,Sphp\Lib\SqlitePdoEngine"; ``` The framework loads the file and constructs `new $class(SphpBase::engine())` — the same constructor shape as every built-in engine. After that change, with **no Gate file edited**, all of these were re-verified on `http://localhost/SartajPhpDoc/`: - `blog.html`, `product.html`, `task.html` — lists, Pagination count queries - `task.html` POST → `insertData()` → `Inserted id=6` - `task-edit-6.html` → `viewData()` fills the form → POST → `Updated id=6` - `task-delete-6.html` → `deleteRec()` → `Deleted id=6` - `pdodemo.html` — raw `$this->dbEngine` SQL listing works unchanged To swap engines **for one request only** (A/B, multi-tenant, reporting DB), replace the engine instance at runtime — Page helpers and `$this->dbEngine` pick it up immediately: ```php <?php // apps/examples/PdoDemo.gate.php — Feature B in the demo gate /** Same shape as the framework engine: constructor takes the Engine wrapper. */ private function swapToPdoEngine() { SphpBase::setDbEngine(new \Sphp\Lib\SqlitePdoEngine(SphpBase::engine())); } /** URL: pdodemo-swapaddnew.html / pdodemo-swappedit-5.html / saveswap / swapdelete */ public function page_event_swappedit($evtp) { $this->swapToPdoEngine(); $form2 = $this->swapFront->getComponent('form2'); $this->page->viewData($form2, $evtp); // inbuilt helper, PDO engine below $this->setFrontFile($this->swapFront); } public function page_event_saveswap($evtp) { $this->swapToPdoEngine(); $form2 = $this->swapFront->getComponent('form2'); $extra = array(); $extra[]['userid'] = 0; $extra[]['parentid'] = 0; $extra[]['spcmpId'] = 'swap'; $extra[]['update_timestamp'] = time(); if ($form2->isUpdateRequest()) { $this->page->updateData($form2, $extra); } else { $extra[]['submit_timestamp'] = time(); $id = $this->page->insertData($form2, $extra); } // ... } ``` Verified: `page->insertData ran through SqlitePdoEngine, id=10`, `page->updateData ran through SqlitePdoEngine (id=1)`, `page->deleteRec ran through SqlitePdoEngine (id=10)` — the helpers never knew the engine underneath them changed. For MySQL with the same custom class, only `connectServer()` changes: ```php public function connectServer($dbHost1, $dbUser1, $dbPass1) { $host = $dbHost1; $port = '3306'; if (strpos($dbHost1, ':') !== false) { list($host, $port) = explode(':', $dbHost1, 2); } self::$dlink = new \PDO("mysql:host=$host;port=$port", $dbUser1, $dbPass1); self::$dlink->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); self::$isConnect = true; $this->pdo = self::$dlink; return true; } ``` That is exactly why the framework's own `MySqliPdo` and `PostgresSqlPdo` can share the same Gates: the Gate codes against the contract, `comp.php` picks the class. ## **12.11 Rules for Third-Party Code in a SartajPHP Gate** 1. **Keep the model framework-free.** Pass a `PDO` (or Doctrine `Connection`) into the constructor. The model stays testable and reusable outside the app. 2. **Build the connection in the Gate**, not in the model — the Gate knows `PROJ_PATH`, `comp.php` settings, and the environment. 3. **Never fight the framework connection.** `Sqlite`/`MySqliPdo` expose `getDatabaseLink()`; opening a second PDO to the same SQLite file is fine for light use. For heavy use, share one connection or move to one layer. 4. **Respect the table conventions** (`id`, `userid`, `parentid`, `submit_timestamp`, `update_timestamp`, `spcmpId`) so Page helpers, data_log, and recycle-bin features keep working on the same tables. 5. **Escape output** (`htmlspecialchars`) when you render model rows yourself — the framework's escaping helpers do not apply to raw strings you build. 6. **Watch class names**: `Pdo`, `Sql`, `Db` etc. can collide with built-in classes (PHP names are case-insensitive). Use `PdoDemo`, `NoteModel`, ... ## **12.12 Swapping in Doctrine / Eloquent** The pattern is identical — only the constructor argument changes: ```php // Doctrine DBAL use Doctrine\DBAL\DriverManager; private function getDoctrine() { return DriverManager::getConnection(array( 'driver' => 'pdo_sqlite', 'path' => PROJ_PATH . '/db/spanel.db', )); } public function page_event_pdolist($evtp) { $conn = $this->getDoctrine(); $rows = $conn->fetchAllAssociative('SELECT * FROM book2_note ORDER BY id DESC'); // ... } ``` Because the Gate is just PHP, any Composer library loaded from `start.php` scope (or `require_once` in the Gate file) works the same way `NoteModel` does here. ## **12.13 Chapter Summary** 1. SartajPHP gates are plain PHP — third-party DB code (PDO, Doctrine, Eloquent) runs beside `dbEngine` and Page helpers on the same tables 2. Build the connection in the Gate (`PROJ_PATH . '/db/spanel.db'`), inject it into a framework-free model class 3. A model can bind to components itself: walk `getAllChildren()`, read `dbField`/`value` where `dataBound` — `insertForm/updateForm/viewForm` mirror the Page helpers over your own PDO (remember `setRecId` in `viewForm`) 4. Page helpers only call `connect / insertSql / updateSql / executeQuery / rowFetchAssoc / lastInsertId / disconnect` on `\SphpBase::dbEngine()` — any object with those methods is a valid engine 5. Write a custom engine exactly like `Sphp\Lib\MySqliPdo`: extend `\Sphp\Kit\DbEngine`, take the Engine wrapper in the constructor, keep the static `$dlink`/`$isConnect` pattern — then Gates need **zero changes**: swap via one `comp.php` `$dbEnginePath` line, or per-request with `SphpBase::setDbEngine(new YourEngine(SphpBase::engine()))` 6. Tested: whole project (blog/product/task + Pagination) ran on the custom `SqlitePdoEngine` with no Gate edits; Page helpers inserted/updated/deleted through it identically to the built-in engine 7. Keep table conventions so framework features (helpers, log, recycle) still work; avoid built-in class-name collisions (`Pdo` → `PdoDemo`) --- **Previous:** [Chapter 11 — Putting It All Together](chapter11.md) · **Next:** [Chapter 13 — AJAX and jsServer](chapter13.md)