# **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
<?php
// apps/Index.gate.php
use Sphp\Gates\BasicGate;
class Index extends BasicGate
{
// Property to hold our FrontFile
private $frtMain;
/**
* Lifecycle Event: onstart
* Called once at the beginning of the request
*/
public function onstart()
{
// use filename for Front file as:- Class name of Gate + _ + filename + .front
// Create FrontFile object
$this->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
> `<title runat="server">` 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*