# **Chapter 1: Gate-Driven Event Architecture - The Core Foundation** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Index.gate.php`) > - Front Files: `*.front` (e.g., `index_main.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** The tested example for this chapter is gate `ex01flow` > (`apps/examples/Ex01flow.gate.php`): open > `http://localhost/SartajPhpDoc/ex01flow.html` (landing URL → `page_new`) and > `http://localhost/SartajPhpDoc/ex01flow-hello-world.html` > (custom event → `page_event_hello($evtp="world")`). --- ## **1.1 What is Gate-Driven Event Architecture?** SartajPhp uses a **Gate-Driven Event Architecture (GDEA)** where an Application can have multiple **Gates**, and each browser request is handled by a specific Gate through a **Page Event**. ### **Understanding Gate vs Application** Think of it this way: - **Application** = Your complete software system (the whole website/app) - **Gate** = An entry point within the Application (like a door/gate) that handles requests for a specific area - **Page Event** = An Event Trigger by Browser URL and handle by a method in your Gate Class - **URL** = Maps to Gate + Event + Parameters ``` Application (Your Website) │ ├── Gate: index → handles index.html, index-view-5.html ├── Gate: blog → handles blog.html, blog-search-php.html ├── Gate: admin → handles admin.html, admin-users.html └── Gate: shop → handles shop.html, shop-products.html ``` **A Gate is the Application's Gate** - it allows user requests to enter into specific parts of your application, processes those requests, and sends responses back to the user. One Application can have multiple Gates, each reserved by a unique "request-word" (the gate name in the URL). ### **How a Gate Works** ``` Browser Request: blog-view-5.html ↓ Gate: blog (reserved word "blog") ↓ Event: view (maps to page_event_view($evtp)) Parameter: 5 (available via $this->page->evtp) ↓ Output: HTML rendered from Front File + Master File ``` The URL segment before the first hyphen (or before .html) is the "request-word" that maps to a specific Gate class. ## **1.2 Why Not MVC?** Traditional MVC has issues as applications grow: - Routes become complex and hard to maintain - Controllers get bloated with too many responsibilities - URL changes break existing code SartajPhp solves this with events: - **No routing configuration needed** - URL directly maps to method - **Natural organization** - Related functionality groups in events - **Easy to extend** - Add new events without changing existing code ## **1.3 The Three Types of Gates** SartajPhp provides different Gate types for different purposes: | Gate Type | Use Case | Extension | |-----------|----------|-----------| | **BasicGate** | Standard web applications | `*.gate.php` | | **NativeGate** | WebSocket/real-time apps | `*.gate.php` | | **ConsoleGate** | CLI applications | `*.gate.php` | For web development, we use `BasicGate`. ## **1.4 BasicGate Structure** Here's what a basic Gate class looks like: ```php page->evtp` | Browser Request GET Landing URL of Gate | | `page_submit()` | `gate.html` | `$this->page->evtp` | Browser POST Request to Landing URL of Gate | ### **Custom Page Events** You can create custom events by naming method `page_event_*` - these DO take `$evtp` directly as a parameter: ```php // URL: gate-login.html → calls page_event_login("") (empty evtp) public function page_event_login($evtp) { } // URL: gate-search-laptop.html → calls page_event_search("laptop") public function page_event_search($evtp) { } // URL: gate-export-pdf.html → calls page_event_export("pdf") public function page_event_export($evtp) { } ``` | Custom Event | URL Pattern | Parameter | |--------------|-------------|-----------| | `page_event_login()` | `gate-login.html` | `$evtp = ""` | | `page_event_search($evtp)` | `gate-search-keyword.html` | `$evtp = "keyword"` | | `page_event_export($evtp)` | `gate-export-format.html` | `$evtp = "format"` | The `$evtp` parameter contains everything after the event name in the URL. ### **Getting Event Parameter in Your Gate** There are multiple ways to access the event parameter: ```php public function page_event_view($evtp) { // Method 1: Direct access to page property $id = $this->page->evtp; // same as $evtp // Method 2: Using Gate helper method $id = $this->getEventParameter(); // same as $evtp // Method 3: Using Page helper method $id = $this->page->getEventParameter(); // // same as $evtp } ``` ## **1.6 URL Translation in Action** Let's see how URLs translate to events: ``` URL: index.html ↓ Gate: index (maps to Index.gate.php) Event: new (maps to page_new()) ↓ Executes: Index::page_new() URL: blog-view-5.html ↓ Gate: blog (maps to Blog.gate.php) Event: view (maps to page_event_view($evtp)) Parameter: 5 (available via $this->page->evtp) ↓ Executes: Blog::page_event_view($evtp) → $this->page->evtp returns "5" URL: shop-search-laptop.html ↓ Gate: shop (maps to Shop.gate.php) Event: search (maps to page_event_search()) Parameter: laptop (passed as $evtp) ↓ Executes: Shop::page_event_search("laptop") ``` **Important:** Built-in page events (`page_new`, `page_submit`, `page_event_*`, etc.) . Custom events (`page_event_*`) DO receive `$evtp` as a parameter. ## **1.7 The Request Flow Diagram** Here's the complete flow when a browser makes a request: ``` ┌─────────────────────────────────────────────────────────┐ │ Browser Request │ │ (index.html) │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ URL Translation Layer │ │ (gate = "index", event = "new") │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ Gate Loader │ │ (Loads Index.gate.php from reg.php) │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ Gate Instantiation │ │ (Creates new Index object) │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ Gate Lifecycle Events │ │ onstart() → onready() → onrun() │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ Page Event Execution │ │ (page_new()) │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ FrontFile Processing │ │ (If setFrontFile is called) │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ MasterFile Merge │ │ (Layout template applied) │ └───────────────────────────┬───────────────────────────────┘ ↓ ┌───────────────────────────▼───────────────────────────────┐ │ HTML Response │ └───────────────────────────────────────────────────────────┘ ``` ## **1.8 Key Concepts Summary** 1. **Gate** - Your application's Gate class that extends BasicGate 2. **Page Event** - Methods in Gate that handle browser requests 3. **URL Pattern** - `--.html` 4. **No Routing** - URL directly maps to Gate + Event method ## **1.9 What's Next?** Now you understand the core architecture. In the next chapter, you'll learn: - How to register your Gate in `reg.php` - How to create your first Gate class - How the URL maps to your Gate's events --- *Next: Chapter 2 - Registering Your First Gate*# **Chapter 2: Registering Your First Gate - From URL to Page Event** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Index.gate.php`) > - Front Files: `*.front` (e.g., `index_main.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** This chapter's flow is the registered gate `ex01flow` > (`apps/examples/Ex01flow.gate.php`, registered in `reg.php`). Open > `http://localhost/SartajPhpDoc/ex01flow.html` and > `http://localhost/SartajPhpDoc/ex01flow-hello-world.html`. --- ## **2.1 The Registration Process** Before your Gate can handle requests, you must register it in the `reg.php` file. This tells SartajPhp which Gate class to load for which URL. ### **The registerGate Function** ```php registerGate("gate_name", "path_to_gate_file.php"); ``` Parameters: - **gate_name** - The word used in URL (e.g., "index" from "index.html") - **path_to_gate_file.php** - Full path to your Gate file ### **Example: Registering the Index Gate** ```php showNotFrontFile(); echo "Home Page"; } /** * Custom Page Event - triggered by URL index-about.html */ public function page_event_about($evtp) { echo "About Page - Parameter: " . $evtp; } /** * Custom Page Event - triggered by URL index-contact.html */ public function page_event_contact($evtp) { echo "Contact Page"; } /** * Form Submit - triggered by URL index.html (POST) * This will not trigger if Form Submit on any other URL like index-form1_submit.html * So you can submit multiple Forms to different Gate's Events with change of URL */ public function page_submit() { echo "Form Submitted!"; } } ``` URL mapping: ``` index.html → Index::page_new() index-about.html → Index::page_event_about("") index-contact.html → Index::page_event_contact("") index.html (POST) → Index::page_submit() ``` ## **2.6 Event Parameter Handling** When your URL includes a parameter, it gets passed to your event method: ```php // URL: blog-view-5.html public function page_event_view($evtp) { // $evtp = "5" echo "Viewing record ID: " . $this->page->evtp; } // URL: user-profile-john.html public function page_event_profile($evtp) { // $evtp = "john" echo "User Profile: " . $evtp; } // URL: shop-search-laptop-price-100.html public function page_event_search($evtp) { // $evtp = "laptop-price-100" // You parse it yourself $parts = explode('-', $evtp); // $parts = ["laptop", "price", "100"] } ``` ## **2.7 Automatic Events** SartajPhp automatically triggers certain events based on form submissions: ```php // Form submission handling only Trigger, Form submit to landing URL like gate.html public function page_submit() { // This is called on form POST /** New Version of SartajPhp removed page_insert, page_update, page_view and page_delete events. * So we need to handle it manually. * Get the HTMLForm component from the FrontFile, then branch on isUpdateRequest(). */ $form2 = $this->frtMain->getComponent('form2'); if ($form2->isUpdateRequest()) { // Encrypted record token (form2re) present = Update existing $this->page->updateData($form2, $this->getExtraFields()); } else { // No record token = Insert new record $this->page->insertData($form2, $this->getExtraFields()); } } // Extra columns not present in the form private function getExtraFields() { $extra = array(); $extra[]['userid'] = 0; $extra[]['parentid'] = 0; $extra[]['submit_timestamp'] = time(); $extra[]['update_timestamp'] = time(); return $extra; } ``` > **Tested pattern:** `$form2->isUpdateRequest()` is true when the form carries the > hidden encrypted record token `form2re` (rendered automatically by `HTMLForm` for > edit requests). See `apps/examples/Blog.gate.php` `page_submit()` for the full > working version, and Chapter 4 for the complete flow. ## **2.8 Chapter Summary** Key points from this chapter: 1. **Register Gate** in `reg.php` using `registerGate("name", "path")` 2. **Create Gate class** extending `BasicGate` 3. **Page Events** are methods like `page_new()`, `page_submit()`, `page_event_name()` 4. **URL maps** directly: `gate-event-parameter.html` → `Gate::page_event_name(parameter)` 5. **Default event** is `page_new()` when no event specified ## **2.9 What's Next?** In the next chapter, you'll learn about Gate lifecycle events (`onstart`, `onready`, `onrun`, `onrender`) and when to use each one for initialization and processing. --- *Next: Chapter 3 - The Gate Lifecycle Events*# **Chapter 3: The Gate Lifecycle Events - Understanding Event Flow** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Index.gate.php`) > - Front Files: `*.front` (e.g., `index_main.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** `apps/examples/Ex02events.gate.php` (gate `ex02events`) traces the > lifecycle live. Open `http://localhost/SartajPhpDoc/ex02events.html` and read the > "Trace" row — it prints the verified order: > `onstart → onfrontinit → onfrontprocess → onready → onrun → page_new`. --- ## **3.1 What are Lifecycle Events?** Lifecycle events are special methods in your Gate class that get called at specific times during request processing. They're different from Page Events (like `page_new()`) because they're triggered automatically by the framework, not by URL requests. Think of lifecycle events as the "behind-the-scenes" setup and teardown of each request. ## **3.2 The Complete Lifecycle Order** Here's when each lifecycle event fires: ``` Request Received ↓ onstart() ← First - Initialize your Gate ↓ FrontFile Loaded (if used) ↓ onfrontinit() ← FrontFile is ready ↓ onfrontprocess() ← FrontFile processed ↓ onready() ← Gate is ready to process ↓ onrun() ← Before Page Event executes ↓ Page Event ← e.g., page_new() or page_event_* ↓ FrontFile Rendered (Components → HTML) ↓ onrender() ← After FrontFile output exists, before Master File ↓ Response Sent ← Final HTML to browser ``` > **Verified:** `ex02events.html` prints > `onstart → onfrontinit → onfrontprocess → onready → onrun → page_new`. > `onrender()` is NOT in that trace — it fires AFTER the FrontFile HTML is > rendered, so a trace string printed by the FrontFile can never contain it. > In `onrender()` you cannot change FrontFile component values anymore; use it > for CSS/JS, Front Places, or replacing output via `SphpBase::$dynData`. ## **3.3 onstart() - The Initialization Event** `onstart()` fires FIRST when your Gate is created. Use it for: - Creating FrontFile objects - Initializing resources - Setting up authentication - Loading configuration ### **Example: Initializing FrontFile in onstart** ```php frtMain = new \Sphp\Tools\FrontFile("main"); } /** * Default Page Event */ public function page_new() { // Use the FrontFile we created in onstart $this->setFrontFile($this->frtMain); } } ``` ### **Example: Authentication in onstart** ```php public function onstart() { // Require ADMIN or MEMBER role $this->getAuthenticate("MEMBER,ADMIN"); // Initialize FrontFile $this->frtMain = new \Sphp\Tools\FrontFile("main"); } ``` ## **3.4 onready() - The Preparation Event** `onready()` fires AFTER FrontFile is parsed and Components are created. Use it for: - Modifying Component properties - Setting default values - Accessing Components by ID - Pre-processing form data ### **Example: Modifying Components in onready** ```php public function onstart() { global $masterf; $this->frtMain = new \Sphp\Tools\FrontFile("form"); $this->setMasterFile($masterf); } public function onready() { // All Components are now created and accessible // Get a text field component $txtName = $this->frtMain->getComponent("txtName"); // Set default value $txtName->fi_setDefaultValue("John Doe"); // Get a dropdown component $sltCountry = $this->frtMain->getComponent("sltCountry"); // Populate options $sltCountry->fu_setOptions("USA,Canada,Mexico,UK"); } ``` ## **3.5 onrun() - The Pre-Processing Event** `onrun()` fires BEFORE the Page Event executes. Use it for: - Final permission checks - Logging - Data pre-processing - Redirects before Page Event runs ### **Example: Pre-Event Processing in onrun** ```php public function onstart() { $this->frtMain = new \Sphp\Tools\FrontFile("dashboard"); } public function onrun() { // Log this access $this->logAccess(); // Check specific permission $this->page->getAuthenticatePerm("view_dashboard"); // Pre-process request data $this->currentPage = $this->client->request("page", 1); } public function page_new() { // By the time we reach here, onrun has already executed $this->setFrontFile($this->frtMain); } ``` ## **3.6 onrender() - The Post-Processing Event** `onrender()` fires AFTER the Page Event completes but BEFORE the final HTML is sent. Use it for: - Adding JavaScript/CSS - Modifying Master File - Adding Front Places - Final output adjustments ### **Example: Post-Processing in onrender** ```php public function onstart() { $this->frtMain = new \Sphp\Tools\FrontFile("page"); } public function page_new() { $this->setFrontFile($this->frtMain); } public function onrender() { // Page Event has executed and FrontFile HTML is rendered (components are // already converted to HTML — change output here via SphpBase::$dynData, // not via component setters) // Add custom CSS, it will send with all type of requests addHeaderCss("app1",'body { font-family: "Manrope", sans-serif; background-color: #f7f9fb; }',false); // Add css or js File Link in HTML Document Output, it will only send with normal request and ignore on AJAX request addFileLink($this->myUrl . "/app1.css", true); // Add css or js File Link in HTML Document Output, it will send on all type requests addFileLink("masters/default/common.js"); // Add custom JavaScript, it will only send with normal request and ignore on AJAX request addHeaderJsCode("app1","console.log('Page rendered!');",true); // Create a Front Place to display sidebar menu in Master File addFrontPlace("sidebar", __DIR__ . "/places/sidebar.place.front"); } ``` ## **3.7 FrontFile Events - Template Interaction** Beyond lifecycle events, you can also handle events from your FrontFile templates: ### **onfrontinit() - FrontFile Parsed, Components Being Created** ```php /** * Trigger for All Front Files Initialize in this Gate File * Fires after the FrontFile Parse Phase (Component oninit/oncreate) and before * Component onaftercreate. Only triggers if a FrontFile is used with the Gate. */ public function onfrontinit($frontobj) { // Sphp\Tools\FrontFile object is now available // $frontobj is the FrontFile instance // Do something with the FrontFile $frontobj->addMetaData("author", "My App"); } ``` > **Tested note:** `addMetaData('title', ...)` does NOT override a > `` component in the FrontFile — the Title component wins. > Use metadata keys of your own (they become `##{$key}#` expressions). See > Chapter 5 and `apps/examples/Blog.gate.php`. ### **onfrontprocess() - FrontFile Processed** ```php /** * Trigger for All Front Files Created in this Gate File * Fires after Component onaftercreate and before onready/onrun. */ public function onfrontprocess($frontobj) { // FrontFile has been fully processed // All Components created, Fusion attributes executed // Can modify components here too (TextField has fu_setReadOnly) $component = $frontobj->getComponentSafe("txtTitle"); if ($component !== null) { $component->fu_setReadOnly(); } } ``` > **Tested note:** use `getComponentSafe('id')` when the component may not exist > in every FrontFile of the Gate — `getComponent()` on a missing id errors. > `fu_setReadOnly()` (no argument) is the verified TextField method; there is no > `fu_setReadonly(true)`. ## **3.8 When to Use Each Event** | Event | When | Best Use For | |-------|------|--------------| | `onstart()` | First | Create FrontFiles, auth check, init | | `onfrontinit()` | After FrontFile parse phase | Set metadata, prepare data | | `onfrontprocess()` | After Components created | Modify Components | | `onready()` | Before Page Event | Modify Components, defaults | | `onrun()` | Just before Page Event | Final checks, logging | | `onrender()` | After FrontFile rendered, before Master File | Add CSS/JS, Front Places, replace output | ## **3.9 Complete Example** Here's a Gate showing all lifecycle events in action: ```php <?php // apps/Product.gate.php use Sphp\Gates\BasicGate; class Product extends BasicGate { private $frtList; // For listing page private $frtEdit; // For edit page /** * Lifecycle Event: onstart * Initialize our FrontFiles here */ public function onstart() { global $masterf; // Require authentication $this->getAuthenticate("MEMBER,ADMIN"); // Create FrontFile objects $this->frtList = new \Sphp\Tools\FrontFile("list"); $this->frtEdit = new \Sphp\Tools\FrontFile("edit"); $this->setMasterFile($masterf); } /** * FrontFile Event: onfrontinit * Called when FrontFile is loaded */ public function onfrontinit($frontobj) { // Add page metadata $frontobj->addMetaData("author", "My App"); } /** * Lifecycle Event: onready * Modify Components before Page Event */ public function onready() { // Set default values for form $this->frtEdit->getComponent("txtDate")->fi_setDefaultValue(date("Y-m-d")); } /** * Lifecycle Event: onrun * Pre-processing before Page Event */ public function onrun() { // Check permission for this specific action if ($this->page->getEvent() === "delete") { // exit process if permission don't match $this->page->getAuthenticatePerm("delete_product"); } } /** * Page Event: page_new * Display product list - URL: product.html */ public function page_new() { // Get products from database $products = $this->getProducts(); // Pass to FrontFile $this->frtList->getComponent("divProducts")->setInnerHtml($products); $this->setFrontFile($this->frtList); } /** * Page Event: page_view * View single product - URL: product-view-5.html */ public function page_event_view($evtp) { // Tested pattern: let the Page helper fill the bound form $form2 = $this->frtEdit->getComponent("form2"); $this->page->viewData($form2, $evtp); $this->setFrontFile($this->frtEdit); } /** * Lifecycle Event: onrender * Add final touches after Page Event */ public function onrender() { // Add analytics (name, code, renderonce) addHeaderJsCode("ga","ga('send', 'pageview');",true); } // Helper methods private function getProducts() { /* ... */ } } ``` ## **3.10 Chapter Summary** 1. **Lifecycle events** fire automatically at specific times during request processing 2. **onstart()** - First, for initialization and FrontFile creation 3. **onfrontinit()** - After FrontFile parse phase, for metadata 4. **onfrontprocess()** - After Components created, for Component modification 5. **onready()** - Before Page Event, for final Component setup 6. **onrun()** - Just before Page Event, for pre-processing 7. **onrender()** - After FrontFile rendered / before Master File, for CSS/JS, Front Places, output replacement 8. **FrontFile events** (`onfrontinit`, `onfrontprocess`) - For template interaction ## **3.11 What's Next?** Now you understand lifecycle events. In the next chapter, you'll learn about Page Events in detail - how to handle different browser requests and form submissions. --- *Next: Chapter 4 - Page Events: Handling Browser Requests*# **Chapter 4: Page Events - Handling Browser Requests** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Blog.gate.php`) > - Front Files: `*.front` (e.g., `blog_list.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** All code in this chapter is tested code from the runnable example > gate `blog` (`apps/examples/Blog.gate.php`). The project runs under the Apache > webroot as subfolder `SartajPhpDoc`. Open > `http://localhost/SartajPhpDoc/blog-install.html` once to create the > `book2_post` table, then `http://localhost/SartajPhpDoc/blog.html`. --- ## **4.1 Understanding Page Events** Page Events are the methods in your Gate class that handle actual browser requests. Unlike lifecycle events which fire automatically, Page Events are triggered by URLs. The URL pattern is: ``` gate-event-parameter.html ``` Examples (all live in the `blog` example): - `blog.html` → Gate: blog, Event: new → `page_new()` - `blog.html` (POST) → Gate: blog, Event: submit → `page_submit()` - `blog-view-5.html` → Gate: blog, Event: view, Parameter: 5 → `page_event_view($evtp)` - `blog-search-php.html` → Gate: blog, Event: search, Parameter: php → `page_event_search($evtp)` ## **4.2 Built-in Page Events** SartajPhp provides two built-in Page Events: `page_new()` for the landing URL (GET) and `page_submit()` for POST to the landing URL. ### **page_new() - Default Page Load** Triggered when browser simply loads the Gate landing URL (GET request). ```php // apps/examples/Blog.gate.php // URL: blog.html public function page_new() { $this->pageName = 'Blog'; if ($this->client->isRequest('q')) { $q = $this->client->request('q'); $this->statusMsg = 'Filtered by q=' . $q . ' (use blog-search-KEYWORD.html too)'; } else { $this->statusMsg = ''; } // The Pagination Component inside blog_list.front renders the posts $this->setFrontFile($this->listFront); } ``` ### **page_submit() - Form Submission** Triggered when a form POSTs to the landing URL. This is the single handler for both insert and update — the form itself knows which mode it is in. ```php // apps/examples/Blog.gate.php // URL: blog.html (POST) — one handler for insert AND update public function page_submit() { $form2 = $this->editFront->getComponent('form2'); // HTMLForm::isUpdateRequest() = true when form carries a RecID (edit) if ($form2->isUpdateRequest()) { $this->doUpdate($form2); } else { $this->doInsert($form2); } } ``` `isUpdateRequest()` is true when the submitted form carries its hidden record token (`form2re`). The framework renders that hidden field for you and encrypts it — after `$this->page->viewData($form2, $evtp)` fills a record, the same POST is an update; an empty form is an insert. ### **Insert New Record** ```php // apps/examples/Blog.gate.php private function doInsert($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->statusMsg = 'Inserted id=' . $id; $this->pageName = 'Blog'; $this->setFrontFile($this->listFront); } else { setErr('blog', 'Insert failed'); $this->setFrontFile($this->editFront); } } ``` `insertData()` collects every Component inside the form that has a `dfield` attribute, builds the INSERT, executes it, and returns the new record ID. `$extra` adds columns that have no Component (timestamps, company id). `getCheckErr()` reports validation errors set by Components or by `setErr()`. ### **Update Existing Record** ```php // apps/examples/Blog.gate.php private function doUpdate($form2) { $extra = array(); $extra[]['update_timestamp'] = time(); $this->page->updateData($form2, $extra); if (!getCheckErr()) { $this->statusMsg = 'Updated id=' . $form2->getRecID(); $this->pageName = 'Blog'; $this->setFrontFile($this->listFront); } else { setErr('blog', 'Update failed'); $this->setFrontFile($this->editFront); } } ``` `updateData()` uses the form's record ID (`$form2->getRecID()`) as the WHERE key. ### **page_event_view($evtp) - Custom Event for View/Edit Single Record** ```php // apps/examples/Blog.gate.php // URL: blog-view-5.html public function page_event_view($evtp) { if ($evtp === '' || $evtp === null) { $this->page_new(); return; } $this->pageName = 'Edit Post'; $this->formButton = 'Update'; $form2 = $this->editFront->getComponent('form2'); // Fill dfield-bound children from table (rec id = event parameter) $this->page->viewData($form2, $evtp); $this->setFrontFile($this->editFront); } ``` ### **page_event_delete($evtp) - Custom Page Event for Delete Record** ```php // apps/examples/Blog.gate.php // URL: blog-delete-5.html public function page_event_delete($evtp) { if ($evtp !== '' && $evtp !== null) { // deleteRec() uses the table set by $this->setTableName() in onstart $this->page->deleteRec($evtp); $this->statusMsg = 'Deleted id=' . $evtp; } $this->pageName = 'Blog'; $this->setFrontFile($this->listFront); } ``` The table for `viewData/insertData/updateData/deleteRec` is set once in `onstart()`: ```php // apps/examples/Blog.gate.php public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); // Default table for Page::insertData / updateData / viewData / deleteRec $this->setTableName('book2_post'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } ``` ## **4.3 Custom Page Events** Create your own events using the `page_event_*` naming pattern. The part of the URL after the event name arrives as `$evtp`. ### **Parameterized Custom Event (search)** ```php // apps/examples/Blog.gate.php // URL: blog-search-KEYWORD.html — $evtp carries the keyword public function page_event_search($evtp) { $this->pageName = 'Search: ' . $evtp; $this->statusMsg = 'Pagination WHERE set from event parameter'; // Restrict the Pagination component query for this request only $showall = $this->listFront->getComponent('showall'); $kw = str_replace("'", "''", (string) $evtp); $showall->fu_setWhere("WHERE txttitle LIKE '%$kw%' ORDER BY id DESC"); $this->setFrontFile($this->listFront); } ``` Try it: `blog-search-Hello.html` shows only posts whose title contains `Hello`. ### **Multiple Parameter Custom Event** `$evtp` contains everything after the event name, so encode multiple values yourself: ```php // URL: shop-filter-electronics-100-500.html public function page_event_filter($evtp) { // $evtp = "electronics-100-500" $parts = explode('-', $evtp); $category = $parts[0]; // "electronics" $minPrice = $parts[1]; // "100" $maxPrice = $parts[2]; // "500" $showall = $this->listFront->getComponent('showall'); $showall->fu_setWhere( "WHERE category='$category' AND price BETWEEN $minPrice AND $maxPrice" ); $this->setFrontFile($this->listFront); } ``` ### **Empty-Parameter Custom Event (addnew)** ```php // apps/examples/Blog.gate.php // URL: blog-addnew.html — empty form (insert mode: form has no RecID) public function page_event_addnew($evtp) { $this->pageName = 'New Post'; $this->formButton = 'Save'; $this->setFrontFile($this->editFront); } ``` ### **AJAX Custom Event** ```php // Called via AJAX: getAjax('blog', 'checktitle', '5') public function page_event_checktitle($evtp) { // $evtp = "5" - post ID $stock = $this->page->viewData($this->editFront->getComponent('form2'), $evtp); // JSON response block for the browser helper $this->jsServer->addJsonReturnBlock([ "post_id" => $evtp, "found" => ($stock !== false) ]); } ``` ## **4.4 Getting Request Data** In your Page Events, access request data using `$this->client` (the Request object; same as `SphpBase::sphpRequest()` outside a Gate). ### **GET Parameters** ```php public function page_new() { // From URL: blog.html?q=php if ($this->client->isRequest('q')) { $q = $this->client->request('q'); // "php" } } ``` ### **POST Parameters (Form Data)** ```php public function page_submit() { $title = $this->client->post('txttitle'); // text field $body = $this->client->post('txabody'); // textarea } ``` ### **All Request Types** ```php public function page_new() { // Get any parameter (GET or POST) $value = $this->client->request('param'); // Get Raw POST data without security filtering, same as $_POST["json1"] $rawData = $this->client->post('json1', true); // Check if parameter exists if ($this->client->isRequest('search')) { // do search } } ``` ## **4.5 Sending Responses** ### **HTML Response (Most Common)** ```php public function page_new() { // Set FrontFile to render (merged with Master File) $this->setFrontFile($this->listFront); } ``` ### **JSON/AJAX Response** ```php public function page_event_checkstock($evtp) { // Send JSON data $this->jsServer->addJsonReturnBlock([ "success" => true, "stock" => 50 ]); // Or update an HTML element by component id $this->jsServer->addJsonHtmlBlock("divStatus", "In Stock!"); // Or execute JavaScript in the browser $this->jsServer->addJsonJsBlock("$('#btnBuy').prop('disabled', false);"); } ``` ### **Redirect Response** ```php public function page_submit() { // After processing, redirect to another page $this->page->forward(getGateUrl("blog")); // Or redirect with event $this->page->forward(getEventUrl("view", $newId)); } ``` ## **4.6 Complete Example - Blog Application** The complete tested Gate (list, install, addnew, view, search, submit, delete): ```php <?php // apps/examples/Blog.gate.php use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class Blog extends BasicGate { /** @var FrontFile list page */ public $listFront = null; /** @var FrontFile edit form */ public $editFront = null; /** @var string heading shown by both fronts */ public $pageName = 'Blog'; /** @var string status line shown on list */ public $statusMsg = ''; /** @var string Save / Update button caption */ public $formButton = 'Save'; public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); $this->setTableName('book2_post'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } public function page_new() { /* list — see 4.2 */ } 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); } public function page_event_addnew($evtp) { /* empty form — see 4.3 */ } public function page_event_view($evtp) { /* viewData — see 4.2 */ } public function page_event_search($evtp) { /* fu_setWhere — see 4.3 */ } public function page_submit() { /* isUpdateRequest — see 4.2 */ } public function page_event_delete($evtp) { /* deleteRec — see 4.2 */ } } ``` The list FrontFile (`apps/examples/fronts/blog_list.front`) uses the Pagination Component so `page_new()` needs no query code at all: ```html <!-- apps/examples/fronts/blog_list.front (excerpt) --> <tbody id="showall" runat="server" path="uikit/data/Pagination.php" fun-setFieldNames="id,txttitle,update_timestamp" dtable="book2_post" fun-setPerPageRows="10" fun-setWhere=" ORDER BY id DESC "> <tr> <td runas="holder" sphp-comp="showall" dfield="id"></td> <td runas="holder" sphp-comp="showall" dfield="txttitle"></td> <td>##{date('Y-m-d H:i', intval($showall->getRow('update_timestamp')))}#</td> <td> <a href="##{getEventUrl('view', $showall->getRow('id'))}#">Edit</a> | <a href="##{getEventUrl('delete', $showall->getRow('id'))}#" onclick="return confirm('Delete?');">Del</a> </td> </tr> </tbody> <div id="pagebar">##{$showall->getPageBar()}#</div> ``` ## **4.7 URL Mapping Reference** | URL | Gate | Event | Parameter | Page Event Called | Parameter Access | |-----|------|-------|-----------|-------------------|------------------| | `blog.html` | blog | new | - | `page_new()` | `$this->client->request('q')` for query string | | `blog.html` (POST) | blog | submit | - | `page_submit()` → insert or update via `isUpdateRequest()` | form components / `$form2->getRecID()` | | `blog-view-5.html` | blog | view | 5 | `page_event_view($evtp)` | `$evtp = "5"` (also `$this->page->evtp`) | | `blog-search-php.html` | blog | search | php | `page_event_search($evtp)` | `$evtp = "php"` | | `blog-addnew.html` | blog | addnew | - | `page_event_addnew($evtp)` | `$evtp = ""` | | `blog-delete-5.html` | blog | delete | 5 | `page_event_delete($evtp)` | `$evtp = "5"` | **Note:** Built-in events are `page_new` and `page_submit`. Custom events (`page_event_*`) receive `$evtp` directly as a method parameter; it is also readable as `$this->page->evtp`. ## **4.8 Chapter Summary** 1. **Page Events** handle browser requests mapped from URLs 2. **Built-in events**: `page_new()` (GET landing URL), `page_submit()` (POST landing URL) 3. **Insert vs update**: one `page_submit()` + `$form->isUpdateRequest()`; save with `$this->page->insertData($form, $extra)` / `updateData($form, $extra)` 4. **Custom events**: `page_event_name($evtp)` — everything after the event name in the URL 5. **Get data**: `$this->client->request()`, `$this->client->post()`, `$this->client->isRequest()` 6. **Send responses**: `setFrontFile()`, `jsServer->addJson*Block()` for AJAX, `page->forward()` for redirect ## **4.9 What's Next?** In the next chapter, you'll learn about FrontFile Events - how to interact with your templates from within your Gate class. --- *Next: Chapter 5 - FrontFile Events: Interacting with Templates* # **Chapter 5: FrontFile Events - Interacting with Templates** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Blog.gate.php`) > - Front Files: `*.front` (e.g., `blog_edit.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** All code in this chapter is tested code from the runnable example > gate `blog` (`apps/examples/Blog.gate.php`). Open > `http://localhost/SartajPhpDoc/blog.html` (list) and `http://localhost/SartajPhpDoc/blog-addnew.html` > (form) — see Chapter 4 for setup. --- ## **5.1 What are FrontFile Events?** FrontFile Events allow your Gate class to interact with the FrontFile template. While Page Events handle browser requests, FrontFile Events handle template interactions. These events are called at specific times during FrontFile processing, allowing you to: - Attach metadata before/after Components are created - Modify Components before rendering - Handle Component-specific init events - Inject dynamic content ## **5.2 The FrontFile Event Methods** ### **onfrontinit($frontobj) - FrontFile Created** Called for **every FrontFile created in the Gate**. Use `addMetaData()` to attach values that FrontFile expressions can read as `##{$key}#`: ```php // apps/examples/Blog.gate.php public function onfrontinit($frontobj) { $frontobj->addMetaData('book2gate', 'blog'); } ``` In any FrontFile of this Gate: ```html <!-- blog_list.front --> <p class="small text-muted">onfrontinit metadata: <code>##{$book2gate}#</code></p> ``` Renders: `onfrontinit metadata: blog` **Important (tested):** `addMetaData('title', ...)` or `addMetaData('description', ...)` does NOT override the `<title runat="server">` component — the title Component drives `<title>`, the description meta tag, and og:title. Set the SEO title by filling the `<title>` component (or a Gate property inside it), and use `addMetaData` for custom keys you read in expressions. ### **onfrontprocess($frontobj) - FrontFile Processed** Called after the FrontFile has been parsed - all Components exist, all fusion attributes executed. Modify Components before rendering: ```php // apps/examples/Blog.gate.php public function onfrontprocess($frontobj) { $p = $frontobj->getComponentSafe('pAdminNote'); if ($p !== null && $this->page->getAuthenticateType() !== 'GUEST') { $p->setInnerHtml('Members/admins see this (onfrontprocess + setInnerHtml).'); } } ``` ```html <!-- blog_list.front — empty container, filled by Gate --> <div id="pAdminNote" runat="server" class="small text-info"></div> ``` `getComponentSafe()` returns `null` instead of throwing when the id is absent — useful when one Gate serves several FrontFiles. **Hide/show tip (tested):** `fu_unsetVisible()` turns the Component tag into a hidden input, but static text around it still prints. For clean show/hide, make the whole element a Component (`runat="server"`) with empty content and fill it from the Gate with `setInnerHtml()` only when it should appear. ## **5.3 Interacting with Components** ### **Getting Components** ```php // Get a specific component by ID $txtTitle = $this->editFront->getComponent('txttitle'); $showall = $this->listFront->getComponent('showall'); $p = $this->listFront->getComponentSafe('pAdminNote'); // null if missing ``` ### **Modifying Components** ```php public function page_event_view($evtp) { // Get component $txtTitle = $this->editFront->getComponent('txttitle'); // Set value (Render Phase) $txtTitle->fu_setValue('Hello Book2'); // Set default value (Parse Phase) $txtTitle->fi_setDefaultValue('Enter a title'); // Make read-only (TextField has fu_setReadOnly — note the capital O) $txtTitle->fu_setReadOnly(); // Hide / show (Render Phase) $txtTitle->fu_unsetVisible(); $txtTitle->fu_setVisible(); // Set inner HTML of a container Component $note = $this->listFront->getComponent('pAdminNote'); $note->setInnerHtml('<p>Dynamic content here</p>'); } ``` | Method | Phase | Purpose | |--------|-------|---------| | `fi_setDefaultValue($val)` | Parse (init) | Default value before form fill | | `fu_setValue($val)` | Render | Value at render time | | `setAttribute($name, $val)` | Any | Raw HTML attribute (readonly, data-*) | | `fu_setVisible()` / `fu_unsetVisible()` | Render | Show / hide the Component | | `setInnerHtml($html)` | Render | Replace inner content | | `getValue()` | Any | Read submitted/current value | ### **Working with Forms** For database operations with forms, use `$this->page` helper methods (see Section 5.8): ```php // apps/examples/Blog.gate.php public function page_submit() { $form2 = $this->editFront->getComponent('form2'); // Check if form is in insert or update mode if ($form2->isUpdateRequest()) { // Edit mode — record id = $form2->getRecID() $this->page->updateData($form2, array()); } else { // New record mode $insertedID = $this->page->insertData($form2, array()); } } // View record for editing public function page_event_view($evtp) { $form2 = $this->editFront->getComponent('form2'); $this->page->viewData($form2, $evtp); $this->setFrontFile($this->editFront); } // Delete record public function page_event_delete($evtp) { $this->page->deleteRec($evtp); } ``` ## **5.4 Component Events from FrontFile** You can also handle events that originate from Components in your FrontFile. ### **Component Event Naming** In your FrontFile, add hooks like `on-init="true"` or `on-startrender="true"`: ```html <input id="txttitle" runat="server" on-init="true"> ``` Then in your Gate, create a method named `comp_{ComponentId}_{event}`: ```php // apps/examples/Blog.gate.php // $arglst['obj'] = Component, $arglst['evt'] = 'on-init' public function comp_txttitle_on_init($arglst) { $comp = $arglst['obj']; $comp->setAttribute('data-book2-init', '1'); } ``` Verified: the rendered input carries `data-book2-init="1"`. ### **Handling Multiple Component Events** ```php // In FrontFile: // <input id="txtEmail" runat="server" on-init="true"> public function comp_txtEmail_on_init($arglst) { $component = $arglst['obj']; // Configure the component early (defaults, flags) $component->fi_setDefaultValue('you@example.com'); } ``` ## **5.5 Using Holder in FrontFile** The `runas="holder"` attribute creates placeholders for dynamic content. The fully tested forms (see Chapter 9 for the complete guide): ```html <!-- Bare holder — Gate must implement onholder($element) --> <div runas="holder"></div> <!-- Fill cell from Pagination Component row field --> <td runas="holder" sphp-comp="showall" dfield="txttitle"></td> <!-- Read a Component property --> <div runas="holder" sphp-comp="showall" sphp-comp-prop="page_links"></div> ``` ### **Setting Holder Content in Gate** ```php // apps/examples/Ex04front.gate.php — bare holder handler public function onholder($element) { // $element is the NodeTag with runas="holder" $element->setInnerHtml('filled by Gate onholder()'); } ``` **Pitfall (tested):** a bare `runas="holder"` without an `onholder()` method in the Gate throws `Call to undefined method ...::onholder()`. For Gate → FrontFile values, the simplest tested mechanism is a Gate property read through an expression — no holder needed: ```php // Gate public $statusMsg = 'Inserted id=3'; ``` ```html <!-- FrontFile --> <p>Status: <code>##{$parentGate->statusMsg}#</code></p> ``` ## **5.6 The onholder Event** `onholder($element)` is called for any holder tag that has no `sphp-comp` source. Branch on your own data attribute to serve several placeholders from one method: ```php // Gate public function onholder($element) { $type = $element->getAttribute('data-widget-type'); switch ($type) { case 'user-list': $element->setInnerHtml($this->getUserListHTML()); break; case 'product-grid': $element->setInnerHtml($this->getProductGridHTML()); break; } } ``` FrontFile: ```html <div runas="holder" data-widget-type="user-list"></div> <div runas="holder" data-widget-type="product-grid"></div> ``` ## **5.7 Complete Example - Blog Application** The tested Blog Gate combines everything in this chapter (full CRUD events in Chapter 4): ```php <?php // apps/examples/Blog.gate.php (FrontFile-event parts) use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class Blog extends BasicGate { public $listFront = null; public $editFront = null; public $pageName = 'Blog'; public $statusMsg = ''; public $formButton = 'Save'; public function onstart() { global $masterf; $this->getAuthenticate('GUEST,MEMBER,ADMIN'); // Default table for $this->page database methods $this->setTableName('book2_post'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } /** Before parse: attach metadata readable as ##{$book2gate}# */ public function onfrontinit($frontobj) { $frontobj->addMetaData('book2gate', 'blog'); } /** After parse: components exist — fill admin note */ public function onfrontprocess($frontobj) { $p = $frontobj->getComponentSafe('pAdminNote'); if ($p !== null && $this->page->getAuthenticateType() !== 'GUEST') { $p->setInnerHtml('Members/admins see this (onfrontprocess + setInnerHtml).'); } } /** Component hook: on-init="true" on #txttitle */ public function comp_txttitle_on_init($arglst) { $arglst['obj']->setAttribute('data-book2-init', '1'); } /** Bare holder fallback (blog_list.front has no bare holder, edit front may add one) */ public function onholder($element) { $element->setInnerHtml('filled by Gate onholder()'); } // page_new / page_submit / page_event_* — see Chapter 4 } ``` ## **5.8 $this->page Helper Methods for Database Operations** SartajPhp provides helper methods through `$this->page` that reduce code when working with database operations. These methods work with Components that have database binding attributes (`dfield` and `dtable`). ### **Setting Table Name** Before using database methods, set the default table name in the Gate: ```php // apps/examples/Blog.gate.php public function onstart() { // ... $this->setTableName('book2_post'); } ``` ### **$this->page->viewData($form, $recID, $fldList, $where)** Fill form components with data from database: ```php public function page_event_view($evtp) { $form2 = $this->editFront->getComponent('form2'); // Fill form with record data ($evtp is the record ID) $this->page->viewData($form2, $evtp); // Or specify custom fields and where clause // $this->page->viewData($form2, '', "txttitle,txabody", "WHERE id=5"); $this->setFrontFile($this->editFront); } ``` ### **$this->page->insertData($form, $extra)** Insert form component values to database; returns the new record ID: ```php public function doInsert($form2) { global $cmpId; $extra = array(); $extra[]['submit_timestamp'] = time(); $extra[]['update_timestamp'] = time(); $extra[]['spcmpId'] = $cmpId; $insertedID = $this->page->insertData($form2, $extra); // check errors: if (!getCheckErr() && $insertedID) { ... } } ``` ### **$this->page->updateData($form, $extra, $recID, $where)** Update existing database record: ```php public function doUpdate($form2) { $extra = array(); $extra[]['update_timestamp'] = time(); // Record id taken from the form itself ($form2->getRecID()) $this->page->updateData($form2, $extra); // Or custom where clause // $this->page->updateData($form2, $extra, '', "WHERE txttitle='Hello Book2'"); } ``` ### **$this->page->deleteRec($recID)** Delete a database record: ```php public function page_event_delete($evtp) { // Delete using event parameter as record ID $this->page->deleteRec($evtp); // Or use the current event parameter implicitly // $this->page->deleteRec(); } ``` ### **Database Binding in FrontFile Components** For `$this->page` helper methods to work, Components need database binding attributes: ```html <!-- apps/examples/fronts/blog_edit.front --> <form id="form2" runat="server" method="post" action="##{getThisGateUrl()}#"> <input id="txttitle" runat="server" type="text" dfield="txttitle" dtable="book2_post" fui-setForm="form2" fun-setRequired="" fun-setMsgName="Title" /> <textarea id="txabody" runat="server" dfield="txabody" dtable="book2_post" fui-setForm="form2"></textarea> <button type="submit">Save</button> </form> ``` - `dfield`: Database table field name - `dtable`: Database table name (optional if `$this->setTableName()` was called) - `fui-setForm`: binds the Component to the form for validation ## **5.9 Chapter Summary** 1. **FrontFile Events** allow Gate-template interaction 2. **onfrontinit($frontobj)** - Called for every FrontFile; `addMetaData` keys read as `##{$key}#` 3. **onfrontprocess($frontobj)** - After parse; modify Components (`getComponentSafe`, `setInnerHtml`) 4. **Component Events** - `on-init="true"` + `comp_componentId_on_init($arglst)` with `$arglst['obj']` 5. **Holders** - `runas="holder"`: bare (needs Gate `onholder`), `sphp-comp` + `dfield`, `sphp-comp-prop` 6. **$this->page helper methods** - `viewData`, `insertData`, `updateData`, `deleteRec` with `dfield`/`dtable` binding and `setTableName()` ## **5.10 What's Next?** Now you understand how Gate interacts with FrontFile. Next, let's build actual webpages using Front Files and Master Files. --- *Next: Chapter 6 - Building Your First Webpage* # **Chapter 6: Building Your First Webpage - Single Front File + Master File** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Index.gate.php`) > - Front Files: `*.front` (e.g., `index_main.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** This chapter's pieces are all tested: > `http://localhost/SartajPhpDoc/ex05master.html` (custom master + Front Place, > `masters/examples/ex05.mast.php`) and `http://localhost/SartajPhpDoc/ex06comp.html` > (form Components + fusion validation). The default master used by most gates is > `masters/default/master.mast.php`. --- ## **6.1 The Page Building Blocks** Before building pages, let's understand the structure: 1. **Gate Class** - Handles logic, events, and data 2. **Front File** (`.front`) - Contains page content (HTML with SartajPhp attributes) 3. **Master File** (`.mast.php`) - Contains page layout (header, footer, menus) The flow: ``` Gate → FrontFile → MasterFile → Browser ``` ## **6.2 Step 1: Register Your Gate** First, register your Gate in `reg.php`: ```php <?php // reg.php // Register the main application registerGate("index", __DIR__ . "/apps/Index.gate.php"); ``` ## **6.3 Step 2: Create the Gate Class** Create `apps/Index.gate.php`: ```php <?php // apps/Index.gate.php use Sphp\Gates\BasicGate; use Sphp\Tools\FrontFile; class Index extends BasicGate { private $frtMain; public function onstart() { global $masterf; // set in comp.php, e.g. "masters/default/master.mast.php" // Create FrontFile object // Front file name = Gate name + "_" + filename + ".front" (apps/fronts/) $this->frtMain = new FrontFile("main"); $this->setMasterFile($masterf); } public function page_new() { // Set the FrontFile to render $this->setFrontFile($this->frtMain); } } ``` ## **6.4 Step 3: Create the Front File** Create `apps/fronts/index_main.front`: ```html <!-- index_main.front - Page Content --> <!-- Page Title (becomes component) --> <title id="pageTitle" runat="server">Welcome

Welcome to My Website

This is the main content of the page.

Loading content...

About Us | Contact

``` This is valid HTML that can be opened in any browser! ## **6.5 Step 4: Create the Master File** Create `masters/default/master.mast.php` (this is the tested project master): ```php getHeaderHTML(); ?>

getFooterHTML(); /* Print all errors related output for debug purposes */ echo SphpBase::sphpApi()->traceError(true) . SphpBase::sphpApi()->traceErrorInner(true); ?> ``` Key points (all verified in the running app): - `addFrontPlace(name, file, section)` **registers** the place file; `runFrontPlace(name, section)` **executes** it; `renderFrontPlace(name, section)` **prints** its output. Order in the master: add → run → (later) render. - `SphpBase::getAppOutput()` is where the rendered FrontFile HTML goes. - `SphpBase::sphpApi()->getHeaderHTML()` / `getFooterHTML()` flush everything added by `addHeaderCss`, `addHeaderJsCode`, `addFileLink`, `addFileLinkCode`, … - `SphpBase::SphpJsM()::addBootStrap()` loads the framework-managed Bootstrap. - `$cmpName` is the project/app name from `comp.php`. ## **6.6 Step 5: Create the Menu (Front Place)** The tested project menu is `masters/default/menu.place.php` — a class extending the framework's `BootstrapMenu`, built with `addMenu` / `addMenuLink`: ```php uiKitPath . "/bundle/menu/BootstrapMenu.php"); /* Create Class name as same as file name */ class menu extends BootstrapMenu{ public function onstart() { $this->sphpApi->addMenu("Home", "","fa fa-home","root"); $this->sphpApi->addMenuLink("Home", SphpBase::sphpSettings()->projectUrl,"fa fa-home","Home"); $this->sphpApi->addMenuLink("Contact Us", getEventUrl('contacts','','index'),"fa fa-fw fa-clock-o","Home"); if(SphpBase::page()->getAuthenticateType() == "GUEST"){ $this->sphpApi->addMenuLink("Login", getGateUrl("signin"),"","Home"); }else{ // roles = auth type and/or permission ids (from registerGate permlist) $this->sphpApi->addMenu("User",'',"fa fa-home","root",false,"ADMIN,MEMBER"); $this->sphpApi->addMenuLink("Users",getGateUrl('mebProfile'),"fa fa-users","User",false,"mebProfile-view"); // ... more links ... } } } ``` A plain HTML place file works too — see the tested `masters/examples/ex05bar.place.front` (a Bootstrap navbar rendered by the custom master `masters/examples/ex05.mast.php`): ```html ``` > **Tested:** a Gate selects a custom master with > `$this->setMasterFile('masters/examples/ex05.mast.php')` (no `global $masterf` > needed then). See `apps/examples/Ex05master.gate.php`. ## **6.7 Complete Flow** Here's what happens when browser requests `index.html`: ``` 1. Browser requests: index.html ↓ 2. Framework finds registered Gate: "index" ↓ 3. Loads: apps/Index.gate.php ↓ 4. Creates: new Index() object ↓ 5. Fires: onstart() - Creates FrontFile object ↓ 6. Fires: page_new() - Calls $this->setFrontFile($this->frtMain) ↓ 7. Framework processes: index_main.front - Parses HTML - Creates Components (runat="server" tags) - Evaluates expressions ↓ 8. Framework merges with: master.mast.php - Adds header/footer - Injects menu from menu.place.front - Puts FrontFile content in
↓ 9. Browser receives complete HTML page ``` ## **6.8 Adding Dynamic Content** Let's enhance our example to show dynamic content: ```php frtMain = new \Sphp\Tools\FrontFile("main"); } public function onready() { // Get dynamic content in onready (after Components created) $content = $this->getLatestNews(); // Inject into FrontFile Component $this->frtMain->getComponent("divContent")->setInnerHtml($content); // Set page title — the Title component renders its INNER HTML into the // browser title + SEO meta, so change the inner HTML: $this->frtMain->getComponent("pageTitle")->setInnerHtml("Home - My Website"); } public function page_new() { $this->setFrontFile($this->frtMain); } private function getLatestNews() { // Simulated database content $news = [ ["title" => "New Product Launch", "date" => "2024-01-15"], ["title" => "Special Offer", "date" => "2024-01-10"], ["title" => "Website Updated", "date" => "2024-01-05"] ]; $html = "

Latest News

    "; foreach ($news as $item) { $html .= "
  • {$item['title']} - {$item['date']}
  • "; } $html .= "
"; return $html; } } ``` ## **6.9 Using Expression Tags in FrontFile** Add dynamic content directly in FrontFile using expression tags (tested forms): ```html ##{$parentGate->pageTitle}#

##{$parentGate->siteName}#

Today's date: ##{date('F j, Y')}#

#{if $parentGate->getAuthenticateType() != 'GUEST'}#

Welcome back!

#{else}#

Login to access member area.

#{endif}#
##{$parentGate->message}#
``` > **Tested SafeEval rules:** expressions run in a sandbox. Use `##{...}#` for > values, `##{raw:...}#` when the value is HTML, and `#{if ...}# ... #{else}# ... > #{endif}#` for blocks. Whitelisted helpers include `date`, `intval`, `time`, > `getGateUrl`, `getEventUrl`, `getThisGateUrl`. PHP casts like `(int)` are NOT > supported — use `intval(...)` instead. Gate properties/methods are reached via > `$parentGate->`. ## **6.10 Adding Components for Interactivity** Add form Components to your FrontFile: ```html

Contact Us

``` ## **6.11 Complete File Structure** Your project should look like this: ``` myproject/ ├── reg.php # Gate registration ├── start.php # Entry point ├── comp.php # Configuration ($masterf, db, ...) │ ├── apps/ │ ├── Index.gate.php # Main Gate │ │ │ └── fronts/ │ ├── index_main.front # Home page │ └── index_contact.front # Contact page (Gate name prefix!) │ └── masters/ └── default/ ├── master.mast.php # Main layout └── menu.place.php # Navigation menu (BootstrapMenu class) ``` > **Tested naming:** `new FrontFile("main")` inside gate `index` loads > `apps/fronts/index_main.front` — the file name is always > `{gatename}_{filename}.front`. ## **6.12 Chapter Summary** 1. **Register Gate** in `reg.php` with `registerGate()` 2. **Create Gate class** extending `BasicGate` 3. **Create Front File** (`.front`) with page content 4. **Create Master File** (`.mast.php`) with layout 5. **Create Front Place** (`.place.front`) for reusable sections like menus 6. Use `$this->setFrontFile()` to render FrontFile 7. Use Components (`runat="server"`) for interactivity 8. Use Expression tags (`##{}#`) for dynamic content ## **6.13 What's Next?** In the next chapter, you'll learn how to use TWO Front Files in one Gate - one for displaying data (Pagination) and one for editing (Form). --- *Next: Chapter 7 - Two Front Files Pattern*# **Chapter 7: Two Front Files Pattern - Pagination and Edit Form** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Product.gate.php`) > - Front Files: `*.front` (e.g., `product_list.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** All code in this chapter is tested code from the runnable example > gate `product` (`apps/examples/Product.gate.php`). Open > `http://localhost/SartajPhpDoc/product-install.html` once, then > `http://localhost/SartajPhpDoc/product.html`. --- ## **7.1 The Two Front Files Pattern** A common pattern in SartajPhp is using **two Front Files** in one Gate: 1. **List Front File** - Displays data with Pagination Component 2. **Edit Front File** - Form for inserting/updating records This pattern provides: - Clean separation between viewing and editing - Reusable pagination for any table - Automatic database operations - Built-in form validation ## **7.2 When to Use This Pattern** Use when your application needs: - List view with pagination - Add new record functionality - Edit existing record functionality - Delete functionality ## **7.3 Step 1: Register the Gate** ```php getAuthenticate('GUEST,MEMBER,ADMIN'); $this->setTableName('book2_product'); $this->listFront = new FrontFile('list'); $this->editFront = new FrontFile('edit'); $this->setMasterFile($masterf); } // Page Events below } ``` ## **7.5 Step 3: Create List Front File with Pagination** Create `apps/examples/fronts/product_list.front`: ```html Products — List

##{$parentGate->pageName}#

Table book2_product · Pagination + AJAX · Status: ##{$parentGate->statusMsg}#

Install schema Add Product Reload

##{raw:traceError(true)}#

ID Name Price Category
$##{$showall->getRow('numprice')}# ##{$showall->getRow('sltcategory')}# Edit | Del
``` ### **How the Pagination Component works** The `` tag becomes a Pagination Component. Its inner markup is a **row template** — the framework repeats it once per database row: | Attribute / syntax | Purpose | |--------------------|---------| | `dtable` | Database table to page through | | `fun-setFieldNames` | Fields to SELECT (comma-separated) | | `fun-setPerPageRows` | Rows per page | | `fun-setWhere` | Extra ORDER BY / WHERE SQL | | `fun-setAJAX` | Page links update via AJAX (no reload) | | `runas="holder" sphp-comp="showall" dfield="id"` | Row cell filled with current row field | | `##{$showall->getRow('numprice')}#` | Expression reading current row field | | `sphp-comp-prop="page_links"` | Page-number links rendered by the Component | Two equivalent ways to print a row value inside the template: - Holder cell: `` - Expression: `##{$showall->getRow('txtname')}#` ## **7.6 Step 4: Create Edit Front File with Form** Create `apps/examples/fronts/product_edit.front`: ```html Product — Form

##{$parentGate->pageName}#

Back to list

##{raw:traceError(true)}#

Cancel
``` ### **Key Form Component Attributes:** | Attribute | Purpose | |-----------|---------| | `dtable` | Database table to bind to | | `dfield` | Database field name | | `fui-setForm` | Bind to form for validation (init phase) | | `fun-setRequired` | Field is required (render phase) | | `fun-setMsgName` | Label used in validation error messages | | `fun-setOptions` | Dropdown options `value=Label,...` | The form posts to `##{getThisGateUrl()}#` — the Gate landing URL — so the POST lands in `page_submit()`. The framework adds a hidden record token automatically; you never render the record id yourself. ## **7.7 Step 5: Add Page Events to Handle Everything** ```php pageName = 'Products'; $this->setFrontFile($this->listFront); } /** URL: product-install.html — create table from db/db_book2.php */ 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: product-create.html — empty form for new record */ public function page_event_create($evtp) { $this->pageName = 'Add Product'; $this->formButton = 'Save'; $this->setFrontFile($this->editFront); } /** URL: product-edit-5.html — form populated with existing data */ public function page_event_edit($evtp) { if ($evtp === '' || $evtp === null) { $this->page_new(); return; } $this->pageName = 'Edit Product'; $this->formButton = 'Update'; $form2 = $this->editFront->getComponent('form2'); $this->page->viewData($form2, $evtp); $this->setFrontFile($this->editFront); } /** URL: product.html (POST) — insert or update */ 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 = 'Products'; $this->setFrontFile($this->listFront); } else { setErr('product', 'Save failed'); $this->setFrontFile($this->editFront); } } /** URL: product-delete-5.html */ public function page_event_delete($evtp) { if ($evtp !== '' && $evtp !== null) { $this->page->deleteRec($evtp); $this->statusMsg = 'Deleted id=' . $evtp; } $this->pageName = 'Products'; $this->setFrontFile($this->listFront); } ``` ## **7.8 URL Mapping Summary** | URL | Event | Action | |-----|-------|--------| | `product.html` | page_new | Show list with pagination | | `product.html` (POST) | page_submit | Save form (insert or update via `isUpdateRequest()`) | | `product-create.html` | page_event_create | Show empty form | | `product-edit-5.html` | page_event_edit | Show populated form | | `product-delete-5.html` | page_event_delete | Delete record | | `product-install.html` | page_event_install | Create table | ## **7.9 How Database Operations Work** ### **Automatic Insert** ```php // Collects form Components with dfield/dtable and inserts $this->page->insertData($form2, $extra); ``` This looks at Components in the form: - `txtname` with `dfield="txtname" dtable="book2_product"` - `numprice` with `dfield="numprice" dtable="book2_product"` - etc. And generates: `INSERT INTO book2_product (txtname, numprice, ...) VALUES (?, ?, ...)` plus the `$extra` columns, then returns the new record ID. ### **Automatic Update** ```php // Collects form Components and updates by the form's record ID $this->page->updateData($form2, $extra); ``` Generates: `UPDATE book2_product SET txtname=?, numprice=? WHERE id=?` ### **Loading Data for Edit** #### **Approach 1: Using $this->page->viewData() (Recommended)** ```php // Auto-populate form from record using database binding // Components need dfield and dtable attributes $this->page->viewData($form2, $recordId); ``` **How viewData works internally (Page::viewData):** ```php // viewData iterates over all form children components $compList = $form2->getAllChildren(); foreach ($compList as $compid => $comp) { // Only process components with dfield attribute and not marked blnDontFill if ($comp->dfield != '' && !$comp->blnDontFill) { // Get table from dtable attribute, else Page::$tblName // (the Gate's default table set via setTableName()) $table = ($comp->dtable != '') ? $comp->dtable : $this->tblName; // Page::$tblName // Build SELECT query, fetch data, set component value from database row } } ``` **Component flags for database binding:** - `dfield`: Database field name to bind with - `dtable`: Database table name (optional, uses `setTableName()` value by default) - `blnDontFill`: When set, component won't be filled from database #### **Approach 2: Manual fetch** ```php // Manual approach - fetch then set each component $this->dbEngine->connect(); $result = $this->dbEngine->executeQuery("SELECT * FROM book2_product WHERE id = $id"); $row = $this->dbEngine->rowFetchAssoc($result); $this->dbEngine->disconnect(); // Set each component manually $this->editFront->getComponent('txtname')->fi_setDefaultValue($row['txtname']); $this->editFront->getComponent('numprice')->fi_setDefaultValue($row['numprice']); ``` #### **FrontFile Component Database Binding** ```html
``` ### **Using Dynamic URLs** Always use `getThisGateUrl()`, `getEventUrl()`, `getGateUrl()` for dynamic URLs instead of hardcoded paths: In FrontFile: ```html Add New Product Edit ``` **Why use these helpers?** - Generates domain-binded absolute URLs (works under Apache subfolders like `/SartajPhpDoc/`) - Works even if you change the Gate registration name in `registerGate()` - Handles URL extensions dynamically ## **7.10 Complete File Structure** ``` SartajPhpDoc/ ├── reg.php │ ├── apps/ │ └── book2/ │ ├── Product.gate.php │ └── fronts/ │ ├── product_list.front # Pagination view │ └── product_edit.front # Add/Edit form │ ├── db/ │ └── db_book2.php # CREATE TABLE book2_product │ └── masters/ └── default/ ├── master.mast.php └── menu.place.php ``` ## **7.11 Chapter Summary** 1. **Two Front Files Pattern** - List for viewing, Form for editing 2. **Pagination Component** - `path="uikit/data/Pagination.php"` with `dtable`, `fun-setFieldNames`, `fun-setPerPageRows`, row cells via `sphp-comp` + `dfield` 3. **Form Components** - Use `dtable` and `dfield` for database binding 4. **Page Events**: - `page_new()` - Show list - `page_event_create()` - Empty form - `page_event_edit($evtp)` - Populated form via `viewData` - `page_submit()` - Save (insert/update via `isUpdateRequest()`) - `page_event_delete($evtp)` - Delete via `deleteRec` 5. **Database Operations** - `page->insertData()`, `page->updateData()`, `page->viewData()` ## **7.12 What's Next?** Next, learn about Master Files - how to create page layouts with headers, footers, and menus. --- *Next: Chapter 8 - Master Files: Creating Page Layouts* # **Chapter 8: Master Files - Creating Page Layouts** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Index.gate.php`) > - Front Files: `*.front` (e.g., `index_main.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** Tested masters in this project: > `masters/default/master.mast.php` (used by `http://localhost/SartajPhpDoc/index.html`) > and the custom `masters/examples/ex05.mast.php` with its Front Place > (`http://localhost/SartajPhpDoc/ex05master.html`). --- ## **8.1 What are Master Files?** Master Files (`.mast.php`) define the overall page layout - the skeleton that wraps your FrontFile content. They contain: - HTML `` section with meta tags and CSS - Page header (logo, navigation) - Main content container - Page footer - JavaScript includes The Master File receives your FrontFile's output and wraps it with the common layout. ## **8.2 Master File Location** Master files are stored in the `masters/` directory: ``` masters/ ├── default/ │ └── master.mast.php # Default layout ├── admin/ │ └── admin.mast.php # Admin area layout └── minimal/ └── simple.mast.php # Minimal layout ``` ## **8.3 Basic Master File Structure** ```php My Website getHeaderHTML(); ?>
getFooterHTML(); ?> ``` ## **8.4 Key Master File Functions** ### **addFrontPlace() - Register a Place** ```php addFrontPlace("name", "path/to/file.place.front", "position"); ``` Parameters: - **name** - Identifier for the place - **path** - Full path to the Front Place file - **position** - Optional position within the place ### **runFrontPlace() - Execute Logic** ```php runFrontPlace("name", "position"); ``` Must be called AFTER `addFrontPlace()` but BEFORE `` ### **renderFrontPlace() - Output Content** ```php ``` Called where you want the content to appear in the HTML. ### **getAppOutput() - FrontFile Content** ```php ``` This is where your FrontFile's rendered HTML appears! ## **8.5 Creating a Menu Front Place** Create `masters/default/menu.main.place.front`: ```html ``` > **Tested:** auth checks use `SphpBase::page()->getAuthenticateType()` > (`'GUEST'`, `'MEMBER'`, `'ADMIN'`) — there is no `isLoggedIn()` / > `getUserName()` on the Gate. Inside `.place.front` files, expression tags and > `getGateUrl` / `getEventUrl` work the same as in normal FrontFiles. For > permission-driven menus use the `BootstrapMenu` class instead (Chapter 6, > `masters/default/menu.place.php`). ## **8.6 Creating a Footer Front Place** Create `masters/default/footer.place.front`: ```html
About Us

We provide quality products and excellent service.

Quick Links
Contact

Email: info@example.com
Phone: (123) 456-7890


© ##{date('Y')}# MyApp. All rights reserved.
``` ## **8.7 Adding Custom CSS/JS to Master File** ### **Adding Custom CSS** ```php ``` ### **Adding Custom JavaScript** ```php ``` ## **8.8 Multiple Master Files** You can have different layouts for different sections. The default master is set in `comp.php` (tested line): ```php setMasterFile('masters/admin/admin.mast.php'); } ``` > **Tested:** `setMasterFile()` is the API — there is no `$this->masterf` property > assignment. See `apps/examples/Ex05master.gate.php`: > `$this->setMasterFile('masters/examples/ex05.mast.php');` (no `global $masterf` > needed when you hardcode the path). ## **8.9 Complete Master File Example** Here's a production-ready Master File: ```php getProp("showSidebar") ?? false; ?> and description meta come from getHeaderHTML() — the Title // component in the FrontFile feeds SphpBase::sphpSettings()->title. echo SphpBase::sphpApi()->getHeaderHTML(); ?> getProp("showBreadcrumb")): ?>
getFooterHTML(); echo SphpBase::sphpApi()->traceError(true); // Show errors in debug mode ?> ``` ## **8.10 How Master File Gets Selected** The Master File to use is configured in `comp.php`: ```php frtMain = new FrontFile("main"); $this->setMasterFile($masterf); } ``` Or override per Gate: ```php public function onstart() { $this->frtMain = new FrontFile("main"); $this->setMasterFile("masters/custom/master.mast.php"); } ``` ## **8.11 Chapter Summary** 1. **Master Files** (`.mast.php`) provide page layout 2. **Front Places** (`.place.front`) provide reusable sections (menu, footer) 3. **addFrontPlace()** - Register a place 4. **runFrontPlace()** - Execute place logic 5. **renderFrontPlace()** - Output place content 6. **getAppOutput()** - Where FrontFile content goes 7. Configure master in `comp.php` or in Gate's `onstart()` ## **8.12 What's Next?** Next, learn about the `runas="holder"` attribute for dynamic content injection in FrontFiles. --- *Next: Chapter 9 - The runas="holder" Attribute*# **Chapter 9: The runas="holder" Attribute - Dynamic Content Injection** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Product.gate.php`) > - Front Files: `*.front` (e.g., `product_page.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** Every holder form in this chapter is tested on the runnable page > `http://localhost/SartajPhpDoc/product-page.html` (gate `product`, > `apps/examples/fronts/product_page.front`). Add a few products first so pagination > has more than one page. --- ## **9.1 What is runas="holder"?** The `runas="holder"` attribute creates a **placeholder** in your FrontFile that gets filled with dynamic content at render time. Unlike `runat="server"` which creates a Component, `runas="holder"` just marks a spot for dynamic content without creating a Component. ## **9.2 Resolution Rules (tested)** A holder is resolved by its helper attributes, in this order: | Used Attributes | Runtime Behavior | Tested? | |-----------------|------------------|---------| | `sphp-comp` + `sphp-comp-prop` | Display **Component property value** | Yes | | `sphp-comp` + `sphp-comp-fun` | Display **Component method return** | Yes | | `sphp-comp` + `dfield` | Display **Component row field** (Pagination/Grid rows) | Yes | | `sphp-comp` only | Trigger **Component `onholder` event**, pass NodeTag | Yes | | none (bare holder) | Trigger **Gate `onholder` event**, pass NodeTag | Yes | | `sphp-app-prop` / `sphp-app-fun` | **Not resolved in current build** — falls through to Gate `onholder` | Yes (see 9.7) | ## **9.3 Bare Holder → Gate onholder()** The simplest form: any tag with `runas="holder"` and no helper attributes is passed to your Gate's `onholder($element)` method. FrontFile: ```html
placeholder
``` Gate: ```php // apps/examples/Product.gate.php public function onholder($element) { // $element is the NodeTag with runas="holder" $element->setInnerHtml('filled by Gate onholder()'); } ``` Output: `
filled by Gate onholder()
` **Pitfall (tested):** a bare holder without an `onholder()` method in the Gate throws `Call to undefined method ...::onholder()`. ## **9.4 One onholder() Serving Many Placeholders** Branch on your own data attribute to serve several placeholders from one method: FrontFile: ```html
counting...
``` Gate: ```php // apps/examples/Product.gate.php public function onholder($element) { $type = $element->getAttribute('data-widget-type'); if ($type === 'stats') { $db = $this->dbEngine; $db->connect(); $result = $db->executeQueryQuick('SELECT COUNT(*) AS c FROM book2_product'); $row = $db->rowFetchAssoc($result); $db->disconnect(); $element->setInnerHtml('Products in DB: ' . (isset($row['c']) ? $row['c'] : '?')); } else { $element->setInnerHtml('filled by Gate onholder()'); } } ``` Output: `Products in DB: 7` ## **9.5 Holder from Component (Pagination rows)** Inside a Pagination/Grid row template, `sphp-comp` + `dfield` prints the current row's field (this is how every list in this book is built): ```html ``` ### **Holder from Component Property** ```html
``` Renders the page-number links: `123` **Tested caveat:** `page_links` is empty until the query actually has more than one page — set `fun-setPerPageRows` small while testing. ### **Holder from Component Method** ```html
``` Same output as the property form above (`getPageBar()` returns `$this->page_links`). ## **9.6 Gate Properties and Methods → Expressions (recommended)** For Gate → FrontFile content, the tested mechanism is the **expression tag**, not a holder attribute: ```php // apps/examples/Product.gate.php /** Gate property */ public $sidebarNote = 'Sidebar from Gate property'; /** Gate method */ public function getCategoryList() { $cats = array('Electronics', 'Clothing', 'Books', 'Home'); $html = '
    '; foreach ($cats as $cat) { $html .= '
  • ' . $cat . '
  • '; } return $html . '
'; } ``` ```html

##{$parentGate->sidebarNote}#

##{raw:$parentGate->getCategoryList()}# ``` - `##{$parentGate->prop}#` — reads a Gate property (escaped). - `##{raw:$parentGate->method()}#` — prints a Gate method's return as raw HTML. - Inside expressions you can also use `$this` for the parent Gate in some contexts; `$parentGate` is the tested, explicit form. ## **9.7 About sphp-app-prop / sphp-app-fun** Older documentation (and some RAG rules) describe: ```html
``` **Tested result (current framework build):** these two attributes are **not resolved** — the holder falls through to the Gate `onholder()` event exactly like a bare holder (both divs above printed `filled by Gate onholder()`). Until they are supported, use: | Instead of | Use | |------------|-----| | `sphp-app-prop="sidebarNote"` | `##{$parentGate->sidebarNote}#` | | `sphp-app-fun="getCategoryList"` | `##{raw:$parentGate->getCategoryList()}#` | Keep an `onholder()` method in any Gate whose FrontFiles contain holders, since unresolved holders route to it. ## **9.8 Practical Example - Dynamic Sidebar** ```php pageName = 'Holder Demo'; $this->setFrontFile($this->pageFront); } ``` ```html
Categories
##{raw:$parentGate->getCategoryList()}#
Note
##{$parentGate->sidebarNote}#
Stats
counting...
``` ## **9.9 Holder vs Component** | Aspect | runat="server" (Component) | runas="holder" | |--------|---------------------------|----------------| | Creates | Component object | No Component | | Use Case | Interactive elements, row templates | Static content slots | | Lifecycle | Has events (on-init, on-startrender, …) | Resolved once at render | | Database | Can use dtable/dfield | `sphp-comp` + `dfield` reads a row field | | Best For | Forms, inputs, interactive | Sidebars, lists, page bars | ## **9.10 Holder with Conditional Logic** Use expression tags for conditional content around holders: ```html #{if $parentGate->getAuthenticateType() != 'GUEST'}#
#{else}#

Login to see stats.

#{endif}# ``` Or conditional class based on a Gate property: ```html
##{$parentGate->statusMessage}#
``` ## **9.10a Expression Tag Rules — What Belongs Inside `##{ }#`** Expression tags are a **controlled subset** of PHP for presentation only. The framework executes them with restricted scope (no project globals — only the component/Gate objects in the template context), and the philosophy is: *simple output, never complex logic.* **✅ Do inside expression tags:** ```html

##{$parentGate->userName}#

##{$parentGate->price * $parentGate->qty}#

##{'Hello ' . $parentGate->firstName}#

##{raw:$parentGate->getCategoryList()}# ``` **❌ Don't:** - Define functions or classes inside a tag - Write loops that build HTML — use a Pagination/loop Component or a Gate method returning the HTML string (the `getCategoryList()` pattern above) - Put business logic or DB access in a tag — prepare data in the Gate, print it in the template - Reach for `$_GET`/`$_POST`/globals — they are not in scope; read `$parentGate->prop` instead The rule of thumb: if an expression needs more than one line to explain, it belongs in a Gate method called via `##{raw:$parentGate->method()}#`. Silent tags `#{ }#` (no output) cover control flow around markup — the `#{if}#`/`#{else}#`/`#{endif}` pattern from 9.10 is the tested form. ## **9.11 Chapter Summary** 1. **runas="holder"** creates placeholder for dynamic content 2. **Bare holder** → Gate `onholder($element)` (required, or exception) 3. **data-widget-type** + `onholder()` switch → many widgets, one handler 4. **sphp-comp + dfield** → Pagination/Grid row field 5. **sphp-comp + sphp-comp-prop / sphp-comp-fun** → Component property / method 6. **Gate properties and methods** → use expressions `##{$parentGate->prop}#` and `##{raw:$parentGate->method()}#` (sphp-app-prop/fun are not resolved in this build) 7. Use holders for sidebars, lists, static content; Components for interactive elements ## **9.12 What's Next?** Next, learn about Code Blocks - how to enhance FrontFile design with reusable styling and layout transformations. --- *Next: Chapter 10 - Code Blocks: Enhancing FrontFile Design* # **Chapter 10: Code Blocks - Enhancing FrontFile Design** > **File Extension Reference:** > - Gate Files: `*.gate.php` (e.g., `Index.gate.php`) > - Front Files: `*.front` (e.g., `index_main.front`) > - Master Files: `*.mast.php` (e.g., `default/master.mast.php`) > - Front Places: `*.place.front` or `*.place.php` > **Try it:** All code in this chapter is tested code from the runnable example > gate `ex08codeblock` (`apps/examples/Ex08codeblock.gate.php` + > `apps/examples/fronts/ex08codeblock_main.front`). Open > `http://localhost/SartajPhpDoc/ex08codeblock.html` — every block below appears > on that page. --- ## **10.1 What are Code Blocks?** Code Blocks (`runcb="true"`) allow you to apply pre-defined styling and layout transformations to any HTML element in your FrontFile without writing custom PHP code. They work similar to CSS utility classes but with server-side processing. Think of code blocks as **reusable design patterns** that transform simple HTML into styled, structured output. | | Code Block | Component | |---|---|---| | Attribute | `runcb="true"` + `sphp-cb-name="..."` | `runat="server"` | | Creates PHP object | No | Yes | | Gate access | No (callback only) | `$front->getComponent('id')` | | Theme changes | Re-register the block — FrontFiles untouched | Edit Gate/Front | ## **10.2 Basic Syntax (tested)** ```html
Body from FrontFile — structure from Code Block card.
sphp-cb-border="3" + sphp-cb-color="primary"
``` - `runcb="true"` — enable code block processing for this tag - `sphp-cb-[blockname]` — apply the named block - **Multiple blocks:** put several `sphp-cb-*` attributes on the same tag > **Tested argument rule:** in this framework build the **whole attribute value > arrives as `$args[0]`** — commas are NOT auto-split. `sphp-cb-card="Header,Footer"` > gives the callback ONE argument `"Header,Footer"`. Either use one value per > attribute (and compose attributes), or split commas yourself inside your own > callback (Section 10.5). ## **10.3 Where Blocks Live** Two layers register blocks with the same registry: 1. **UI kit (shared):** `vendor/sartajphp/sartajphp/res/components/uikitdef/bootstrap/sphpcodeblock.php` 2. **Project (theme):** `masters/sphpcodeblock.php` — included by the UI-kit file at its end, so the project file can **add new blocks** or **re-register an existing name to override it** (theme change without editing FrontFiles). ## **10.4 Shared UI-Kit Blocks (verified in this install)** From the vendor `sphpcodeblock.php` — these all work out of the box: | Block | Value | Effect (verified) | |-------|-------|-------------------| | `card` | title **or** image path | Bootstrap card; value with `.` → ``, else `card-header`; `class` option wraps body in `card-body` | | `border` | `0-5`, `top`, `end`, `bottom`, `start` | `border` / `border-N` classes | | `color` | `primary`…`dark` | text/bg color class | | `shadow` | empty/`1`/`2`/`3` | `shadow`, `shadow-sm`, `shadow-lg`, `shadow-none` | | `size` | `1-5` | `w-25`…`w-100`, `w-auto` | | `rounded` | `0-3`, `circle`, `pill`, sides | `rounded-*` | | `align` | `left/center/right` | `d-flex justify-content-*` | | `overflow` | `1-3` | `overflow-scroll/hidden/visible` | | `text` | align/size args | text classes | | `position` | `left/center/right` | positioning wrapper | | `label` | label text (+sizes) | Bootstrap horizontal form row around an input | | `btn-count`, `btn-marker` | color | button classes | | `bggrad` | colors | gradient background | | `aos`, `counter` | animation args | scroll animations (not in AJAX mode) | Usage (from the tested `ex08codeblock_main.front`): ```html
…
…
Expect class shadow-lg
``` ## **10.5 Defining Your Own Blocks (`masters/sphpcodeblock.php`)** Callback signature: `function ($element, $args, $lstOther_CB)` where `$element` is the HTML node (methods: `appendAttribute`, `appendPreTag`, `appendPostTag`, `appendInnerPreTag`, `setInnerPreTag`, …), `$args` is the argument list, and `$lstOther_CB` carries block options (e.g. `class`). Tested project blocks: ```php appendAttribute('class', ' alert alert-info'); $element->appendInnerPreTag('' . htmlspecialchars($title) . ': '); }, array('documentation' => 'Ex08 callout. Value = title.') ); // Project-only panel with comma args split in the callback: // sphp-cb-ex08panel="Title,Footer" SphpCodeBlock::addCodeBlock( 'ex08panel', function ($element, $args, $lstOther_CB) { $args = sphp_ex08_split_args($args); $title = isset($args[0]) ? $args[0] : ''; $footer = isset($args[1]) ? $args[1] : ''; $pre = '
'; if ($title !== '') { $pre .= '
' . htmlspecialchars($title) . '
'; } $pre .= '
'; $element->appendPreTag($pre); $post = '
'; if ($footer !== '') { $post .= ''; } $post .= '
'; $element->appendPostTag($post); }, array('documentation' => 'Ex08 panel. Value title,footer (comma-split in project callback).') ); ``` ## **10.6 Overriding a Shared Block (Project Theme)** Re-calling `SphpCodeBlock::addCodeBlock` with an existing name **replaces** that block. Tested override of the UI-kit `shadow` — FrontFiles keep using `sphp-cb-shadow`, but the project version adds its own marker: ```php 'shadow-sm', 2 => 'shadow-lg', 3 => 'shadow-none'); $n = intval($args[0]); $element->appendAttribute('class', ' ' . (isset($ch[$n]) ? $ch[$n] : 'shadow')); } else { $element->appendAttribute('class', ' shadow'); } $element->setAttribute('data-ex08-shadow', 'project'); }, array('documentation' => 'Project override of UI-kit shadow.') ); ``` Verified output on `ex08codeblock.html`: the demo div gets `class="... shadow-lg"` **and** `data-ex08-shadow="project"` — proof the project block ran instead of the UI-kit one. ## **10.7 Practical Example — Product Card Without PHP** The shared `card` block already covers the classic product-card layout — its first argument is a **title or an image path** (value containing `.` renders `card-img-top`), and the `class` option wraps content in `card-body`: ```html
Product Name

Description goes here.

Card with text header.

``` For a title **and** footer in one attribute, use a project block with the comma-split helper (10.5): ```html
Comma args split inside the project callback (title + footer).
``` ## **10.8 Code Blocks vs Components** | Feature | Code Blocks | Components | |---------|-------------|-------------| | Syntax | `runcb="true"` | `runat="server"` | | Creates Object | No | Yes | | Interactive | No | Yes | | Database Binding | No | Yes (dtable/dfield) | | Gate access | Callback only | `getComponent()` / `comp_*_on_*` hooks | | Best For | Styling, layout | Forms, data display | | Complexity | Low | Higher | ## **10.9 Chapter Summary** 1. **Code Blocks** (`runcb="true"` + `sphp-cb-[name]`) transform plain tags server-side 2. **One value per attribute** in this build — `$args[0]` is the whole string; split commas yourself in your callback when you need multi-args 3. **Compose** multiple blocks by adding multiple `sphp-cb-*` attributes 4. **Define** project blocks in `masters/sphpcodeblock.php`; re-registering a shared name overrides it (theme without touching FrontFiles) 5. **Shared UI-kit blocks** (`card`, `border`, `color`, `shadow`, `size`, `rounded`, `align`, `label`, …) work out of the box — verified on `ex08codeblock.html` 6. Use code blocks for **styling/layout**, components for **interactive/data** tags --- *Next: Chapter 11 - Putting It All Together* # **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 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 Task Manager

##{$parentGate->pageName}#

Table book2_task · Status: ##{$parentGate->statusMsg}# · Gate meta: ##{$book2gate}#

Install schema + New Task Reload

##{raw:traceError(true)}#

ID Title Priority Status Due
##{$showall->getRow('sltpriority')}# ##{$showall->getRow('sltstatus')}# ##{$showall->getRow('datdue_date')}# Edit | Del
``` Note the conditional badge class inside the row template — expressions work per row: ```html ``` ## **11.6 Step 4: Create Edit Front File** ```html Task Form

##{$parentGate->pageName}#

Back to list

##{raw:traceError(true)}#

Cancel #{if $parentGate->isEditMode}#
Delete
#{else}# #{endif}#
``` 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 getHeaderHTML(); ?> getFooterHTML(); echo SphpBase::sphpApi()->traceError(true) . SphpBase::sphpApi()->traceErrorInner(true); ?> ``` ## **11.8 Step 6: Menu Front Place** ```php ``` ## **11.9 Step 7: The Table (db/db_book2.php)** ```php 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.