PHPue
Documentation

Introduction

PHPue is a PHP framework that brings the simplicity of Vue's component model to server-side rendering. Build modern web applications without the complexity of build tools or client-side hydration.

What is PHPue?

A PHP framework that uses Vue-like syntax for server-side rendering. Write components with familiar directives, but get pure HTML from the server. Zero JavaScript required for core functionality.

Tutorials

Learn PHPue through step-by-step tutorials designed for developers of all skill levels. Our tutorials cover everything from basic setup to advanced features.

🎓 Interactive Learning Platform

PHPue includes a complete tutorial system built with PHPue itself. Each tutorial provides hands-on examples and real-world scenarios.

Getting Started

  • • Setting up your development environment
  • • Creating your first PHPue application
  • • Understanding the file structure

What's Included

  • • Step-by-step video guides
  • • Interactive code examples
  • • OS-specific installation guides
📚 Explore PHPue Tutorials

All tutorials are built with PHPue and demonstrate real-world usage patterns.

Tutorial Structure

Beginner-Friendly: Start from zero knowledge and progress to advanced topics
Practical Examples: Every concept is demonstrated with working code
Self-Contained: Each tutorial can be followed independently
Built with PHPue: The tutorial system itself is a PHPue application

Get Started

Start building with PHPue in minutes. No complex setup, no build process, just pure PHP power.

Terminal
# Clone the starter template
git clone https://github.com/PHPue/PHPue my-app
cd my-app/www

# Start the development server
php -S localhost:8000

Installation

PHPue Framework requires PHP 8.0+ and works with any web server. No additional extensions needed.

Manual Installation

  1. Download PHPue core files | PHPue - GitHub
  2. Include in your project.
  3. You may need to configure your server to point to the index.php file
    as the entry point. - View .htaccess example
  4. Start building views and components.
  5. Syntax Highlighting: Download PHPue Syntax Highlighter |
    VSCode Extension - GitHub

File Structure

PHPue follows a convention-based structure that makes organising your application intuitive and scalable.

Project Structure

# Root Directory
www/
App.pvue
index.php
conversion.php
assets/
css/
js/
components/
dashboards/
forms/
Navbar.pvue
views/
index.pvue
about.pvue
docs.pvue
features.pvue
.dist/
# Auto-generated files
pages/
ajax/

# Core files
App.pvue
assets/
components/

Core Files

  • App.pvue - Main application layout and routing
  • index.php - Application server / builder
  • conversion.php - Build engine for PVue files
  • pvue-injections.json - Auto-injection configuration for syntax highlighting

Directories

  • views/ - Page components with routing
  • components/ - Reusable UI components
  • assets/ - Static files (CSS, JS, images)
  • .dist/ - Compiled PHP files (auto-generated)

Naming Conventions

Views: Use descriptive names (about.pvue, docs.pvue)
Components: Use PascalCase (Navbar.pvue, Sidebar.pvue)
Terminal
[skira24@SK14 PHPue]$ cd www
[skira24@SK14 www]$ ls
App.pvue components pvue-injections.json views
assets conversion.php index.php tailwind.config.js
[skira24@SK14 www]$ cd assets
[skira24@SK14 assets]$ ls
css js
[skira24@SK14 assets]$ cd ../components/
[skira24@SK14 components]$ ls
codeBlocks dashboards forms Navbar.pvue navigation
[skira24@SK14 components]$ cd ../views/
[skira24@SK14 views]$ ls
about.pvue a-get-started.pvue b-sponser.pvue docs.pvue features.pvue index.pvue

Deployment

PHPue offers two deployment strategies - choose the one that fits your workflow and security requirements.

🚀

Option 1: Build Locally

Recommended for production - Compile locally and deploy only the optimised files.

# Build locally
cd www/
php -S localhost:3000
Visit: localhost:3000?build=1
# Deploy to server via FTP:
📁 .dist/
📁 httpReqs/
📁 assets/
📄 index.php
📄 conversion.php
# NEW: Deploy (Version 0.0.2)
📁 ajax/
📁 components/
📁 pages/
📁 httpReqs/
📁 assets/
📄 App.php
📄 index.php
📄 conversion.php

✅ Advantages

  • • No source code on production server
  • • Better performance (pre-compiled)
  • • No security risks from exposed .pvue files
  • • Smaller deployment footprint
  • • (Optional:) Block access to .dist/ (OR) any business logic directories.
⚡

Option 2: Deploy Source

For development or when you need instant builds on the server.

# Deploy all files via FTP:
📁 components/
📁 views/
📁 assets/
📄 *.pvue files
📄 index.php
📄 conversion.php
# Build on server:
Visit: yourdomain.com?build=1

⚠️ Security Required

  • • Must block .pvue files in .htaccess/NGINX
  • • Protect App.pvue, components/, views/, other exposed directories. directories
  • • Source files expose business logic if accessible

🔒 Essential Security Configuration

If you choose Option 2, you MUST add these security rules to prevent source code exposure.

Apache (.htaccess)

# BLOCK access to all .pvue files (anywhere)
<FilesMatch "\.pvue$">
    Require all denied
</FilesMatch>

# BLOCK access to assets/, views/, and components/
RewriteRule ^(views|components)(/.*)?$ - [F,L]

✅ Blocks all .pvue files and protects source directories

NGINX

# BLOCK .pvue files
location ~ \.pvue$ {
    deny all;
    return 404;
}

# BLOCK source directories
location ~ /(views|components)/ {
    deny all;
    return 404;
}

✅ Equivalent protection for NGINX servers

🛡️ Production Safety Feature

PHPue automatically prevents accidental rebuilds on production servers for your protection.

# If .dist/ exists (production):
Visit: yourdomain.com?build=1
❌ Build disabled - .dist/ directory already exists
This appears to be a production environment
To force rebuild, use: php index.php build

This prevents accidental rebuilds that could break your live site. For intentional rebuilds, use the CLI command.

🚀 Quick Start Guide

1

Develop Locally

Build your app with php -S localhost:3000

2

Build & Test

Run ?build=1 to compile to .dist/

3

Deploy Safely

Upload only .dist/, index.php, and conversion.php

💡 Pro Tip: Always build locally and deploy the compiled .dist/ directory for maximum security and performance.

@require & #require

Import components and views using simple require statements.

Component Require

@require ComponentName 'components/componentName.pvue';

Import a component for use in your template.

View Require

#require 'views/viewName.pvue';

Include a view template with its own logic.

Example: App.pvue

Here's how you might structure your main application file:

<script>
    @require Navbar 'components/Navbar.pvue';
    #require 'views/index.pvue';
    #require 'views/about.pvue';
</script>

<header>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="assets/css/styles.css">
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <script src="assets/js/jquery-3.7.1.min.js"></script>
</header>

<template>
    <Navbar></Navbar>
    <View></View>
</template>

Key Points:

  • @require imports reusable components
  • #require imports views for routing
  • <header> block for global assets and meta tags
  • <View> component automatically handles current page rendering

Template Blocks

PHPue components are structured using familiar blocks for different concerns.

<script>
// PHP logic here
$title = "Hello World";
$users = $db->query("SELECT * FROM users")->fetchAll();
</script>

<header>
    <title>{{ $title }}</title>
    <meta name="description" content="My PHPue app">
</header>

<template>
    <!-- Your HTML template -->
    <div p-for="$user in $users">
        {{ $user->name }}
    </div>
</template>

<cscript>
// Client-side JavaScript (optional)
console.log('Component mounted');
</cscript>

Directives

Use Vue-like directives for common tasks. All processing happens on the server.

p-if

<div p-if="$user->isAdmin">Admin Content</div>

Conditionally render elements based on PHP expressions.

p-for

<li p-for="$item in $items"></li>

Loop through arrays and objects to render lists.

Form Handling Philosophy

Privacy-First Form Design

PHPue respects user privacy by avoiding automatic form tracking. Instead of two-way data binding that monitors every keystroke, we encourage explicit form submissions with clear user intent.

// views/contact.pvue - Complete form example
<script>
    @AJAX('POST')
    function ajaxFormSubmit($input) {
        $formData = $input['formData'] ?? [];
        
        // Store in session to use later
        $_SESSION['subForm_email'] = $formData['email'] ?? '';
    }
</script>

<template>
    <form onsubmit="handleSubmit(event, 'ajaxFormSubmit')">
        <input name="email" type="email">
        <button type="submit">Submit</button>
    </form>
</template>

<cscript>
    let emailAddr = '';

    async function handleSubmit(event, methodName) {
        event.preventDefault();
        const formData = new FormData(event.target);

        const response = await fetch('', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                action: methodName,
                formData: Object.fromEntries(formData)
            })
        });

        if (response.status === 200) {
            emailAddr = {{ $_SESSION['subForm_email'] }};
        }
    }
</cscript>

💡 Note: We use explicit form submission instead of automatic tracking. Users must intentionally click "Submit" - no passive data collection. - It is super easy to either modify the framework to support p-model (the logic for the REGEX is already there), or to implement your own two-way binding with the power of PHPue's AJAX capabilities and CSR support for tracking.

Respect user privacy with explicit form handling patterns.

Hot Reload

Instant browser refreshes when you edit your .pvue or PHP files. See changes in real-time without manual reloading.

🚀 Quick Start

1

Start Development Server

cd www && php -S localhost:3000
2

Enable Hot Reload

Visit any page with ?live parameter:

localhost:3000/your-page?live
3

Start Coding

Edit any .pvue file and watch the browser refresh automatically! 🔥

🐳 Docker Compose Advantage

Using Docker? Hot reload works even better with full AJAX support!

# Start with Docker (recommended)
docker compose up
# Hot reload is automatically enabled
# AJAX works perfectly with NGINX

⚠️ Important Notes

PHP Built-in Server: Hot reload works. However, AJAX may not function properly
NGINX (Docker): Hot reload + AJAX work perfectly together
Production: Hot reload is automatically disabled in production builds

💡 Pro Tip: Use Docker Compose for the best development experience with full hot reload and AJAX support!

AJAX Functions

Create server-side AJAX handlers with simple annotations.

@AJAX('POST')
function saveUser($input) {
    // Handle form submission
    return ['success' => true];
}
@AJAX('GET')
function updateSession() {
    if(isset($_GET['token'])) {
        $_SESSION['userToken'] = $_GET['token'];
    }
}

HTTP Error Pages

PHPue automatically handles 404 errors with support of customisable error pages. Create beautifully styled 404 pages that match your application's design.

(Optional) File Structure for 404 Pages

# Create these files in your httpReqs directory
httpReqs/
http404.php (Optional or will fall back to Framework 404 Handler
http404Head.php (Optional or will fall back to Framework 404 Header)

Current Support: Only 404 pages are supported in this version.

Example: Custom 404 Page

Create a user-friendly 404 page that helps users navigate back to your application:

httpReqs/http404Head.php
<?php
    global $phpue_header;
    $phpue_header = <<<HTML
        <script src="https://cdn.tailwindcss.com"></script>
        <title>404 - Page Not Found</title>
        <meta name="description" content="The page you're looking for doesn't exist">
        <meta name="keywords" content="404, page not found">
        <meta name="author" content="Edward Patch">
    HTML;

    $GLOBALS['phpue_http404_header'] = $phpue_header;
?>
httpReqs/http404.php
<!-- APP WRAPPER -->
<div class="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex items-center justify-center p-4">
    <div class="max-w-md w-full text-center">
        <div class="text-6xl mb-4">🔍</div>
        <h1 class="text-2xl font-bold text-gray-900 mb-2">Page Not Found</h1>
        <p class="text-gray-600 mb-6">
            Sorry, we couldn't find the page you're looking for. 
            The page might have been moved or deleted.
        </p>
        <div class="space-y-3">
            <a href="/" class="block w-full bg-emerald-600 hover:bg-emerald-700 text-white font-medium py-3 px-6 rounded-lg transition duration-200">
                Return to Homepage
            </a>
            <button onclick="history.back()" class="w-full border border-gray-300 hover:bg-gray-50 text-gray-700 font-medium py-3 px-6 rounded-lg transition duration-200">
                Go Back
            </button>
        </div>
    </div>
</div>
<!-- END OF APP WRAPPER -->
Live Preview
🔍

Page Not Found

Sorry, we couldn't find the page you're looking for. The page might have been moved or deleted.

Best Practices for 404 Pages

Keep it simple: Clear messaging with minimal technical jargon
Provide clear actions: Include prominent buttons to go home or back
Use friendly visuals: Add icons or illustrations to soften the error
Search functionality: Consider adding a search box for content discovery
Be helpful: Suggest what the user can do next
Note: Your app's navigation and branding are automatically included!

Backend Directory

Extend PHPue with custom PHP classes and vendor libraries using the backend/ directory. All classes are auto-loaded when the framework starts, making them available throughout your application. PHPue 0.0.2 fully supports Composer vendor directories and automatically detects autoload.php files.

Directory Structure

# Backend Directory
backend/
DBLoader.php
AuthManager.php
EmailService.php
vendor/

Auto-loading: All PHP files in backend/ are automatically included when the framework initialises. Vendor directories with autoload.php are fully supported. You can also create a custom autoload.php to control load order.

How Backend Auto-loading Works

1
Framework Initialisation

PHPue scans the backend/ directory on startup

2
Auto-include Classes

All .php files in the backend directory are automatically included.

3
Vendor Support

If backend/vendor/autoload.php exists, PHPue automatically requires it, enabling full Composer vendor support (PSR-4, classmap, and files).

4
Optional Autoload Ordering

Create a custom autoload.php in any directory and add your require statements to control class load order. PHPue will load classes in the specified order and skip the brute-force scan for that directory.

5
Ready to Use

Your classes are now available throughout the application via singleton patterns or direct instantiation.

Example: Database Loader Class

Create a singleton database manager that's available throughout your application:

// backend/DBLoader.php

<?php
    class SimpleDB {
        private static ?self $instance = null;

        public static function getInstance(): self
        {
            if(self::$instance === null)
                self::$instance = new self();

            return self::$instance;
        }

        public function getMessage(): string
        {
            return "Hello from backend class!";
        }

        public function getUsers(): array
        {
            return [
                ['id' => 1, 'name' => 'John'],
                ['id' => 2, 'name' => 'Jane'],
            ];
        }
    }
?>
Usage in Components
// In any .pvue file script section
<script>
  $db = SimpleDB::getInstance();
  $users = $db->getUsers();
</script>

Vendor Libraries (Experimental)

PHPue 0.0.2 fully supports Composer vendor directories and automatically detects autoload.php. Simple libraries like Parsedown work out of the box. Complex dependencies may still require manual testing or a custom autoload.php.

Current Support Level

✅ Fully Supported: Composer vendor directories
🔧 Needs Testing: Large multi-package ecosystems

Manual Vendor Setup (Optional)
# Download vendor library manually

cd backend

mkdir -p vendor

wget https://github.com/erusev/parsedown/archive/1.7.4.zip

unzip 1.7.4.zip -d vendor/

# Result: backend/vendor/parsedown-1.7.4/Parsedown.php

PHPue will automatically find and load Parsedown.php or any autoload.php in backend/vendor/.

💡
Important Usage Guidance
  • • Load dependencies before initialising singletons
  • • If dependencies are in the same file, call Class::getInstance() immediately
  • • Otherwise, initialise classes in App.pvue, views/, or components/
  • • Use a custom autoload.php to control load order and prevent brute-force scanning

Complex libraries may still require testing, but following this sequence ensures best results.

Best Practices

Use Singleton Pattern for resource-heavy classes
Implement proper exception handling
Use environment variables for sensitive configuration
Organise classes with namespaces
Use PHP 8+ type hints
Include PHPDoc for IDE support

Common Backend Classes

Database Managers
  • • DBLoader - Database connections
  • • UserRepository - User data access
  • • CacheManager - Caching layer
Service Classes
  • • EmailService - Email delivery
  • • AuthManager - Authentication
  • • FileUploader - File handling
Utility Classes
  • • Logger - Application logging
  • • Validator - Data validation
  • • Formatter - Data formatting