Documentation

On this page

Download full book (text)

# **Chapter 23: Component Internals — Lifecycle, Custom Components, and ComponentGroup** > **Prerequisites:** Chapters 5, 6, 17 (FrontFiles, Components in use, fusion rules) > **Try it:** Tested code from gates `ex06comp` and `ex06group` > (`apps/examples/Ex06comp.gate.php`, `apps/examples/Ex06group.gate.php`), > the project Component `comp/form/PhoneField.php`, and the ComponentGroup > `comp/calculator/Calculator.php` + `comp/calculator/CompGates/Calculator.cgate.php`. > Open `http://localhost/SartajPhpDoc/ex06comp.html` and > `http://localhost/SartajPhpDoc/ex06group.html`. --- ## **23.1 Two Objects, One Tag** Every `runat="server"` tag becomes a **pair**: - the **Component object** (PHP class) — state, validation, DB binding, events - the **NodeTag** (`$component->element`) — the HTML element it renders into The Component writes through the NodeTag (`setAttribute`, `setInnerHtml`, `wrapTag`…) and reads posted values through itself (`getValue()`). Chapters 5-17 used this from the Gate side; this chapter is about what happens **inside** a Component — so you can build your own. ## **23.2 The Component Lifecycle (Verified Order)** Override points from `\Sphp\Tools\Component` (`vendor/sartajphp/sartajphp/res/Score/SphpDoc/Sphp/Tools/Component.php`), in trigger order: ``` Parse phase (during new FrontFile(...)) oninit() — set defaults; before any children init [Gate hook comp_{id}_on_init via on-init="true"] [fui-* fusion methods execute] oncreate($element) — all static + fui-* attributes readable onaftercreate() — every Component of the Front exists now Request processing values populate from POST/GET; form validation runs Gate event phase ongateevent() — Component may answer its own PageEvents/AJAX Render phase (only if the Front renders and renderMe is true) onprejsrender() — before children's JS; create shared JS functions onprerender() — before children render [fur-* / fun-* fusion methods execute] onjsrender() — after children rendered; add JS/CSS links onrender() — write the HTML layout onpostrender() — finalize / cleanup Non-lifecycle hooks onchildevent($event, $obj) — first-level children's oncreate/onrender onholder($obj) — runas="holder" with sphp-comp pointing here onparse($event, $domelem) — during parseHtml() of runtime HTML ``` Two practical consequences: 1. **Anything that must exist before a Page Event runs** (validation rules, upload paths, default values) belongs in `oninit`/`oncreate` — the parse phase. This is why FileUploader settings are `fui-*` (Chapter 17). 2. **Anything producing output** (JS, CSS, HTML) belongs in the render-phase handlers, which never run when the Component's output is suppressed (`fu_unsetRender`, AJAX partials). ## **23.3 Gate Hooks: `comp_{id}_on_{event}`** A Gate can borrow a Component's lifecycle without writing a Component class. Add `on-init="true"` / `on-startrender="true"` to the tag, then name the Gate method `comp_{componentId}_{event}` (tested in `Ex06comp.gate.php`): ```html <input id="txtPhone" runat="server" type="text" path="myPath/../../../comp/form/PhoneField.php" on-init="true" on-startrender="true" ... /> ``` ```php <?php // apps/examples/Ex06comp.gate.php (tested) public function comp_txtPhone_on_init($arglst) { $comp = $arglst['obj']; // the Component $this->compHookLog .= 'init:' . $arglst['evt'] . ';'; $comp->setAttribute('data-ex06-init', '1'); } public function comp_txtPhone_on_startrender($arglst) { $arglst['obj']->setAttribute('data-ex06-hook', $arglst['evt']); } ``` `$arglst['obj']` is the Component, `$arglst['evt']` the event name. Use hooks for one-off page logic; promote to a Component class when two pages need it. ## **23.4 A Custom Component: `PhoneField`** `comp/form/PhoneField.php` (loaded by the `path=` attribute above) is the minimal complete custom Component: extend the closest built-in, add a fusion method, add JS. Every piece is one line of intent: ```php <?php // comp/form/PhoneField.php (tested — powers the phone input on ex06comp.html) include_once(\SphpBase::sphpSettings()->uiKitPath . '/form/TextField.php'); class PhoneField extends \Sphp\Comp\Form\TextField { private $phoneMinDigits = 10; protected function oninit() { parent::oninit(); $this->setAttributeDefault('inputmode', 'tel'); // parse phase, cheap $this->setAttributeDefault('autocomplete', 'tel'); } /** Fusion: fui-setPhoneMinDigits / fun-setPhoneMinDigits */ public function fi_setPhoneMinDigits($n) { $this->phoneMinDigits = (int) $n; if ($this->issubmit) { // server-side check $digits = preg_replace('/\D+/', '', (string) $this->value); if (strlen($digits) < $this->phoneMinDigits) { $this->setErrMsg($this->getAttribute('msgname') . ' needs at least ' . $this->phoneMinDigits . ' digits'); } } } protected function onjsrender() // render phase JS { parent::onjsrender(); $id = $this->name; addFooterJSCode('phonefield_' . $id, ' (function () { var el = document.getElementById("' . $id . '"); if (!el || el.getAttribute("data-phonefield") === "1") return; el.setAttribute("data-phonefield", "1"); el.addEventListener("input", function () { /* format (XXX) XXX-XXXX */ }); })(); ', true); // true = renderonce — safe under AJAX re-render } } ``` The rules this demonstrates: | Rule | Where it shows | |------|----------------| | Extend the nearest built-in, call `parent::` in every override | `oninit`, `onjsrender` | | Fusion methods are **public** with `fi_`/`fu_` prefix | `fi_setPhoneMinDigits` → `fui-setPhoneMinDigits` | | Validate server-side in the `fi_*` method (`$this->issubmit`) | digit check | | Inject JS in `onjsrender` with a unique block id + `renderonce` | `addFooterJSCode(..., true)` | | Guard against double-init on AJAX re-render | `data-phonefield` marker | | Document fusion methods for tooling | `genhelpPropList()` + `addHelpPropFunList` | The same skeleton wraps any JS plugin: load the plugin's CSS/JS in `onjsrender`, then initialize it on `$this->name` (the tag id). ## **23.5 ComponentGroup + CompGate: A Component With Its Own App** A `ComponentGroup` (`\Sphp\Tools\ComponentGroup`) is a Component that ships a **whole UI with its own events**: its design comes from a child FrontFile rendered by a private **CompGate** (`*.cgate.php`), not from PHP echo. The tested Calculator proves the pattern with three small files. **1. The Component** — `comp/calculator/Calculator.php`: ```php <?php class Calculator extends \Sphp\Tools\ComponentGroup { public function oninit() { $this->registerEvent("SendFull"); // custom events the parent Gate $this->registerEvent("result"); // can subscribe to } public function onprejsrender() { $this->raiseEvent("SendFull"); // fires during render } } ``` **2. The CompGate** — `comp/calculator/CompGates/Calculator.cgate.php` (same class name as the Component, namespace `Sphp\CompGates`, **not** registered in `reg.php`): ```php <?php namespace Sphp\CompGates; class Calculator extends \Sphp\Gates\CompGate { private $front1 = null; public function onstart() { $this->front1 = new \Sphp\Tools\FrontFileComp( $this->myPath . '/fronts/calculator.child.front', $this); $this->setFrontFile($this->front1); // this HTML becomes the component output } public function page_event_calup($evtp) { // AJAX submit inside the widget $num1 = floatval($this->front1->getComponent($this->nameprefix . "num1")->getValue()); $num2 = floatval($this->front1->getComponent($this->nameprefix . "num2")->getValue()); $this->jsServer->addJsonHtmlBlock("caldiv1", "Result:- " . ($num1 + $num2)); $this->parentComponent->raiseEvent("result", ["result" => $num1 + $num2]); } } ``` **3. The parent Gate embeds it with one tag** (`ex06group_main.front`): ```html <div id="cal1" runat="server" path="myPath/../../../comp/calculator/Calculator.php"> Calculator placeholder (replaced by CompGate child FrontFile) </div> ``` and subscribes to its custom events manually (tested in `Ex06group.gate.php`): ```php <?php public function onstart() { // ... $cal = $this->frtMain->getComponent('cal1'); $this->setEventHandler($cal, 'SendFull'); // → comp_cal1_SendFull($arglst) $this->setEventHandler($cal, 'result'); // → comp_cal1_result($arglst) } public function comp_cal1_result($arglst) { $this->groupEventLog .= 'result=' . $arglst['result'] . ';'; } ``` The three rules that make CompGate behave (from the vendor class docs): 1. **Name prefixing** — `FrontFileComp` prefixes every child Component id with the group id: `num1` inside `cal1` becomes `cal1num1` in the parent Front and in browser JS. That is why the CompGate reads `$this->nameprefix . "num1"`. No name collisions, ever. 2. **Event order** — the CompGate's `onstart` runs after the registered Gate's `onstart/onready/onrun`, but its **PageEvents run before** the parent Gate's PageEvents (handled inside `ongateevent`). `ongateevent` and `onprerender` are therefore final in `ComponentGroup` — don't override them. 3. **Custom events ≠ lifecycle hooks** — `registerEvent`/`raiseEvent` events route only through `setEventHandler` in the parent Gate (handler name `comp_{id}_{EventName}`), unlike `on-init`/`on-startrender` which bind by attribute. ## **23.6 Which Mechanism When** | Need | Use | |------|-----| | One page tweaks one Component | Gate hook `comp_{id}_on_init` | | Reusable behavior/validation/JS across pages | Custom Component extending a built-in (23.4) | | Self-contained widget with own UI + AJAX + events | ComponentGroup + CompGate (23.5) | | Repeated rows of anything | Pagination/DataGrid + holders (Chapters 7, 15) | | Dynamic plain HTML attributes | `fur-_` (Chapter 17) | ## **23.7 Verify It Yourself** Against `http://localhost/SartajPhpDoc/`: 1. `ex06comp.html` → hooks log shows `init:on-init;startrender:on-startrender;` — parse- and render-phase hooks fired in order 2. Type digits into Phone → formats as `(XXX) XXX-XXXX` live (onjsrender JS) 3. Submit with < 10 digits → "Phone needs at least 10 digits" (`fi_*` validation) 4. `ex06group.html` → calculator UI renders inside the page (CompGate Front) 5. Event log shows `SendFull;` (raised from `onprejsrender`) 6. Enter two numbers → result appears inside the widget (CompGate AJAX), and after the AJAX the parent log shows `result=…` (`raiseEvent` → `setEventHandler`) 7. Inspect source: child inputs are `cal1num1`, `cal1num2` — name prefixing --- **Previous:** [Chapter 22 — NativeGate](chapter22.md) · **Next:** [Appendix A — Minimum Project Files](appendixA.md)