Documentation

On this page

Download full book (text)

# **Chapter 11: Putting It All Together - Complete Example** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Task.gate.php`) > - Front Files: `*.front` (e.g., `task_list.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** This chapter's Task Manager is the tested gate `task` > (`apps/examples/Task.gate.php`). Open `http://localhost/SartajPhpDoc/task-install.html` > once, then `http://localhost/SartajPhpDoc/task.html`. --- ## **11.1 The Complete Project** In this chapter, we build a complete **Task Manager** application that demonstrates: - Gate registration and URL mapping - Lifecycle events (onstart, onfrontinit) - Page Events (list, create, edit, search, delete, submit) - Two Front Files pattern (list + edit) - Master File with navigation - Holders and expressions ## **11.2 Project Structure** ``` SartajPhpDoc/ ├── reg.php # Gate registration ├── comp.php # Configuration ├── start.php # Entry point │ ├── apps/ │ └── book2/ │ ├── Task.gate.php # Main Gate │ └── fronts/ │ ├── task_list.front # List view with pagination │ └── task_edit.front # Add/Edit form │ ├── db/ │ └── db_book2.php # CREATE TABLE book2_task │ └── masters/ └── default/ ├── master.mast.php # Layout └── menu.place.php # Navigation ``` ## **11.3 Step 1: Register the Gate** ```php <?php // reg.php registerGate("task", __DIR__ . "/apps/examples/Task.gate.php"); ``` ## **11.4 Step 2: Create the Gate Class** ```php <?php // apps/examples/Task.gate.php use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class Task extends BasicGate { /** @var FrontFile list view with pagination */ public $listFront = null; /** @var FrontFile add/edit form */ public $editFront = null; public $pageName = 'Task Manager'; public $statusMsg = ''; public $formButton = 'Save'; /** true = edit mode (edit front shows Update + Delete) */ public $isEditMode = false; public $recordId = ''; public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); $this->setTableName('book2_task'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } /** Before parse: metadata readable as ##{$book2gate}# */ public function onfrontinit($frontobj) { $frontobj->addMetaData('book2gate', 'task'); } /** URL: task.html — Pagination renders the list */ public function page_new() { $this->pageName = 'Task Manager'; $this->setFrontFile($this->listFront); } /** URL: task-install.html */ public function page_event_install($evtp) { $db = $this->dbEngine; $db->connect(); include_once(SphpBase::sphpSettings()->getProjectPath() . '/db/db_book2.php'); $db->disconnect(); $this->statusMsg = 'Installed book2 tables (db/db_book2.php)'; $this->setFrontFile($this->listFront); } /** URL: task-create.html — empty form */ public function page_event_create($evtp) { $this->pageName = 'Create New Task'; $this->formButton = 'Create Task'; $this->isEditMode = false; $this->recordId = ''; $this->setFrontFile($this->editFront); } /** URL: task-edit-5.html — form filled by viewData */ public function page_event_edit($evtp) { if ($evtp === '' || $evtp === null) { $this->page_new(); return; } $this->pageName = 'Edit Task'; $this->formButton = 'Update'; $this->isEditMode = true; $this->recordId = $evtp; $form2 = $this->editFront->getComponent('form2'); $this->page->viewData($form2, $evtp); $this->setFrontFile($this->editFront); } /** URL: task-search-KEYWORD.html (or task-search.html?q=KEYWORD from the form) */ public function page_event_search($evtp) { $kw = (string) $evtp; if ($kw === '' && $this->client->isRequest('q')) { $kw = (string) $this->client->request('q'); } $this->pageName = 'Search: ' . $kw; $showall = $this->listFront->getComponent('showall'); $kw = str_replace("'", "''", $kw); $showall->fu_setWhere("WHERE txttitle LIKE '%$kw%' ORDER BY id DESC"); $this->setFrontFile($this->listFront); } /** URL: task.html (POST) */ public function page_submit() { $form2 = $this->editFront->getComponent('form2'); if ($form2->isUpdateRequest()) { $extra = array(); $extra[]['update_timestamp'] = time(); $this->page->updateData($form2, $extra); $ok = !getCheckErr(); $this->statusMsg = $ok ? 'Updated id=' . $form2->getRecID() : 'Update failed'; } else { 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); $ok = !getCheckErr() && $id; $this->statusMsg = $ok ? 'Inserted id=' . $id : 'Insert failed'; } if ($ok) { $this->pageName = 'Task Manager'; $this->setFrontFile($this->listFront); } else { setErr('task', 'Save failed'); $this->setFrontFile($this->editFront); } } /** URL: task-delete-5.html */ public function page_event_delete($evtp) { if ($evtp !== '' && $evtp !== null) { $this->page->deleteRec($evtp); $this->statusMsg = 'Deleted id=' . $evtp; } $this->pageName = 'Task Manager'; $this->setFrontFile($this->listFront); } } ``` ## **11.5 Step 3: Create List Front File** ```html <!-- apps/examples/fronts/task_list.front --> <title id="title1" runat="server">Task Manager</title> <h1>##{$parentGate->pageName}#</h1> <p class="text-muted small"> Table <code>book2_task</code> · Status: <code>##{$parentGate->statusMsg}#</code> · Gate meta: <code>##{$book2gate}#</code> </p> <p> <a class="btn btn-sm btn-primary" href="##{getEventUrl('install')}#">Install schema</a> <a class="btn btn-sm btn-success" href="##{getEventUrl('create')}#">+ New Task</a> <a class="btn btn-sm btn-outline-secondary" href="##{getGateUrl('task')}#">Reload</a> </p> <p class="small text-danger">##{raw:traceError(true)}#</p> <!-- Search: submits to task-search-KEYWORD.html --> <form action="##{getEventUrl('search')}#" method="get" class="mb-3" style="max-width:420px"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search tasks..."> <button type="submit" class="btn btn-outline-secondary">Search</button> </div> </form> <table class="table table-striped table-sm"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Priority</th> <th>Status</th> <th>Due</th> <th></th> </tr> </thead> <tbody id="showall" runat="server" path="uikit/data/Pagination.php" fun-setFieldNames="id,txttitle,sltpriority,sltstatus,datdue_date" dtable="book2_task" fun-setPerPageRows="5" fun-setWhere=" ORDER BY id DESC "> <tr> <td runas="holder" sphp-comp="showall" dfield="id"></td> <td><strong runas="holder" sphp-comp="showall" dfield="txttitle"></strong></td> <td> <span class="badge bg-##{($showall->getRow('sltpriority') == 'High') ? 'danger' : 'secondary'}#"> ##{$showall->getRow('sltpriority')}# </span> </td> <td>##{$showall->getRow('sltstatus')}#</td> <td>##{$showall->getRow('datdue_date')}#</td> <td> <a href="##{getEventUrl('edit', $showall->getRow('id'))}#">Edit</a> | <a href="##{getEventUrl('delete', $showall->getRow('id'))}#" onclick="return confirm('Delete?');">Del</a> </td> </tr> </tbody> </table> <div id="pagebar" runas="holder" sphp-comp="showall" sphp-comp-prop="page_links"></div> ``` Note the conditional badge class inside the row template — expressions work per row: ```html <span class="badge bg-##{($showall->getRow('sltpriority') == 'High') ? 'danger' : 'secondary'}#"> ``` ## **11.6 Step 4: Create Edit Front File** ```html <!-- apps/examples/fronts/task_edit.front --> <title id="title1" runat="server">Task Form</title> <h1>##{$parentGate->pageName}#</h1> <p><a href="##{getGateUrl('task')}#">Back to list</a></p> <p class="small text-danger">##{raw:traceError(true)}#</p> <form id="form2" runat="server" method="post" action="##{getThisGateUrl()}#" class="mb-4"> <div class="mb-3"> <label class="form-label">Task Title *</label> <input id="txttitle" runat="server" type="text" class="form-control" dfield="txttitle" dtable="book2_task" fui-setForm="form2" fun-setRequired="" fun-setMsgName="Title" /> </div> <div class="mb-3"> <label class="form-label">Description</label> <textarea id="txadescription" runat="server" class="form-control" rows="4" dfield="txadescription" dtable="book2_task" fui-setForm="form2"></textarea> </div> <div class="mb-3"> <label class="form-label">Priority</label> <select id="sltpriority" runat="server" class="form-select" dfield="sltpriority" dtable="book2_task" fui-setForm="form2" fun-setOptions="Low=Low,Medium=Medium,High=High,Urgent=Urgent"></select> </div> <div class="mb-3"> <label class="form-label">Status</label> <select id="sltstatus" runat="server" class="form-select" dfield="sltstatus" dtable="book2_task" fui-setForm="form2" fun-setOptions="Pending=Pending,In Progress=In Progress,Completed=Completed"></select> </div> <div class="mb-3"> <label class="form-label">Due Date</label> <input id="datdue_date" runat="server" type="date" class="form-control" dfield="datdue_date" dtable="book2_task" fui-setForm="form2" /> </div> <div class="d-flex justify-content-between"> <a href="##{getGateUrl('task')}#" class="btn btn-secondary">Cancel</a> #{if $parentGate->isEditMode}# <div> <button type="submit" class="btn btn-primary">Update</button> <a href="##{getEventUrl('delete', $parentGate->recordId)}#" class="btn btn-danger" onclick="return confirm('Delete this task?')">Delete</a> </div> #{else}# <button type="submit" class="btn btn-success">Create Task</button> #{endif}# </div> </form> ``` The `#{if}#` control structure switches the buttons between create and edit mode using the Gate property `$isEditMode` — no per-component work needed. ## **11.7 Step 5: Master File** The Task gate uses the project master `masters/default/master.mast.php` (set via `global $masterf; $this->setMasterFile($masterf);` in `onstart`). Its structure is covered fully in Chapter 8: ```php <?php // masters/default/master.mast.php (excerpt) addFrontPlace("menu", __DIR__ . "/menu.place.php", "left"); runFrontPlace("menu", "left"); ?> <!DOCTYPE html> <html> <head lang="en"> <meta http-equiv="Content-Type" content="text/html; charset=utf8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php SphpBase::SphpJsM()::addBootStrap(); echo SphpBase::sphpApi()->getHeaderHTML(); ?> </head> <body> <!-- ... header + renderFrontPlace("menu", "left") ... --> <?php SphpBase::getAppOutput(); ?> <?php echo SphpBase::sphpApi()->getFooterHTML(); echo SphpBase::sphpApi()->traceError(true) . SphpBase::sphpApi()->traceErrorInner(true); ?> </body> </html> ``` ## **11.8 Step 6: Menu Front Place** ```php <?php // masters/default/menu.place.php (excerpt) // A Front Place is a small PHP/front fragment rendered inside the master. ?> <ul class="nav"> <li class="nav-item"><a class="nav-link" href="##{getGateUrl('index')}#">Home</a></li> <li class="nav-item"><a class="nav-link" href="##{getGateUrl('task')}#">Tasks</a></li> </ul> ``` ## **11.9 Step 7: The Table (db/db_book2.php)** ```php <?php // db/db_book2.php (excerpt — SQLite branch) $sql = "CREATE TABLE IF NOT EXISTS book2_task ( id INTEGER PRIMARY KEY AUTOINCREMENT, userid BIGINT NOT NULL DEFAULT 0, parentid BIGINT NOT NULL DEFAULT 0, txttitle VARCHAR(150) NOT NULL, txadescription TEXT, sltpriority VARCHAR(20) NOT NULL DEFAULT 'Medium', sltstatus VARCHAR(20) NOT NULL DEFAULT 'Pending', datdue_date VARCHAR(20), submit_timestamp VARCHAR(20) NOT NULL, update_timestamp VARCHAR(20) NOT NULL, spcmpId VARCHAR(14) )"; $mysql->createTable($sql); ``` Required helper columns: `id` (PK), `submit_timestamp`, `update_timestamp`, `spcmpId` (see `db/db_index.php` header). ## **11.10 URL Mapping Summary** | URL | Gate | Event | Parameter | Result | |-----|------|-------|-----------|--------| | `task.html` | task | new | - | Show list with pagination | | `task.html` (POST) | task | submit | - | Save form (insert/update via `isUpdateRequest()`) | | `task-create.html` | task | create | - | Show empty form | | `task-edit-5.html` | task | edit | 5 | Show populated form | | `task-delete-5.html` | task | delete | 5 | Delete task | | `task-search-work.html` | task | search | work | Search results | | `task-search.html?q=work` | task | search | - | Same search via query string | | `task-install.html` | task | install | - | Create table | ## **11.11 Complete Flow Summary** 1. **Browser requests** `task.html` 2. **Framework** finds "task" in reg.php, loads Task.gate.php 3. **onstart()** creates FrontFile objects, checks authentication, sets table 4. **onfrontinit()** attaches metadata (`##{$book2gate}#`) 5. **page_new()** sets FrontFile; Pagination Component queries `book2_task` 6. **Master File** wraps output with layout + menu Front Place 7. **Browser receives** complete HTML page 8. Clicking **Edit** → `task-edit-5.html` → `viewData()` fills form → POST back → `isUpdateRequest()` → `updateData()` → list again with status message ## **11.12 Chapter Summary** This chapter demonstrated the complete development flow: 1. **Registration** - `registerGate()` in reg.php 2. **Gate Class** - Extends BasicGate, handles events 3. **Lifecycle Events** - onstart, onfrontinit 4. **Page Events** - page_new, page_submit, page_event_* 5. **Two Front Files** - List view + Edit form 6. **Master File** - Layout with menu Front Place 7. **Holders + Expressions** - Row cells, page bar, conditional buttons ## **What You've Learned** - How URL maps to Gate + Event - Gate lifecycle events and when to use each - Page events for different request types - FrontFile events for template interaction - Building pages with FrontFiles and Master Files - Two Front Files pattern for list/edit - Holders and expressions for dynamic content **You are now ready to build web applications with SartajPhp!** --- **Next:** Chapter 12 shows how third-party database code (plain PDO / model classes) can live alongside SartajPhp's own database layer.