Skip to content

Core Concepts: App & Component

Everything in PhpSPA revolves around two main classes: App and Component.

  • App


    This is the main container for your entire application. It holds your layout and manages all your components.

  • Component


    This is a reusable piece of your UI. Think of it as a simple PHP function that outputs HTML.

Simple Workflow

You create one App instance, create your Components, and then attach them to the app.


Required Namespaces

All PhpSPA applications require these namespace imports:

<?php
use PhpSPA\App;
use PhpSPA\Component;
Include these at the top of your PHP files.


Here's how they work together:

1. Define a Layout

<?php

$Layout = function () {
   return '<div id="app"></div>';
};

The layout defines where components will render.

2. Create the App

<?php

$app = new App($Layout);

Initialize the main application with your layout.

3. Build a Component

<?php

$homePage = new Component(function () {
   return "<h1>Welcome to the Home Page!</h1>";
});

Components are functions that return HTML.

4. Set the Route

<?php

$homePage->route('/');

Configure which URL path triggers this component.

5. Attach to App

<?php

$app->attach($homePage);

Register the component with the application.

6. Run the Application

<?php

$app->run();

Render the page.


Complete Example

<?php

use PhpSPA\App;
use PhpSPA\Component;

$Layout = function () {
   return '<div id="app"></div>';
};

$app = new App($Layout);

$homePage = new Component(function () {
   return "<h1>Welcome to the Home Page!</h1>";
});

$homePage->route('/');
$app->attach($homePage);
$app->run();