Module Development Guide

Learn how to create powerful, professional modules for PhPstrap using our comprehensive example template

1. Getting Started

PhPstrap modules are self-contained packages that extend your application's functionality. Our example module demonstrates all the essential patterns you need to build professional modules.

Prerequisites

  • PHP 8.0 or higher
  • PhPstrap framework installed
  • MySQL/MariaDB database
  • Basic understanding of PHP OOP
Quick Start

Download our example module and follow this guide to customize it for your needs.

Download Example

2. File Structure

A well-organized module follows this structure:

modules/your_module/
your_module/
├── YourModule.php          # Main module class
├── install.php             # Installation script
├── uninstall.php           # Uninstallation script
├── module.json             # Module configuration
├── assets/
│   ├── your-module.css     # Styles
│   └── your-module.js      # JavaScript
├── views/
│   ├── form.php           # Frontend forms
│   ├── widget.php         # Widget templates
│   └── admin-settings.php # Admin interface
└── languages/             # Translations (optional)
    └── your-module-en.po
Core Files
YourModule.php Main functionality and logic
install.php Database setup and registration
module.json Metadata and configuration
Optional Files
uninstall.php Clean removal script
assets/ CSS, JS, and images
views/ HTML templates

3. Main Module Class

The main module class is the heart of your module. Here's the basic structure:

YourModule.php
<?php

namespace PhPstrap\Modules\YourModule;

use Exception;
use PDO;

class YourModule
{
    private $pdo;
    private $settings;
    private $module_path;
    private $version = '1.0.0';
    
    public function __construct()
    {
        $this->module_path = dirname(__FILE__);
        $this->loadSettings();
        $this->initDatabase();
    }
    
    public function init()
    {
        if (!$this->settings['enabled']) {
            return;
        }
        
        $this->registerHooks();
        $this->loadAssets();
        
        if ($this->isAdmin()) {
            $this->registerAdminMenu();
        }
    }
    
    // Your module methods here...
}
Constructor

Initialize paths, load settings, and set up database connection.

Init Method

Register hooks, load assets, and set up admin interface.

Custom Methods

Add your specific functionality and business logic.

4. Installation Script

The installation script sets up your module in the PhPstrap system:

Key Functions
  • create_tables()
    Set up database tables
  • register_module()
    Add to modules registry
  • setup_permissions()
    Configure user permissions
Installation Commands
php install.php Run installation script directly
Through PhPstrap Admin
Upload module ZIP and install via admin panel
Example Settings Structure
function get_default_module_settings() {
    return [
        'enabled' => true,
        'welcome_title' => 'Welcome!',
        'max_items' => 10,
        'debug_mode' => false
        // Simple values only - no complex objects!
    ];
}

5. Module Configuration

The module.json file contains metadata and configuration:

module.json Example
{
    "name": "your_module",
    "title": "Your Module Title",
    "description": "What your module does",
    "version": "1.0.0",
    "author": "Your Name",
    "namespace": "PhPstrap\\Modules\\YourModule",
    "settings": {
        "enabled": true,
        "welcome_title": "Default Title",
        "max_items": 10
    },
    "permissions": [
        "your_module_view",
        "your_module_admin"
    ],
    "hooks": [
        "your_module_init",
        "your_module_loaded"
    ]
}
Configuration Tips
Name
Use lowercase with underscores
Version
Follow semantic versioning
Settings
Simple values only!

6. Frontend Assets

CSS Structure
/* CSS Variables for theming */
:root {
    --module-primary: #007bff;
    --module-spacing: 1rem;
}

/* Component styles */
.your-module-widget {
    padding: var(--module-spacing);
    border: 1px solid #ddd;
    border-radius: 0.375rem;
}

/* Responsive design */
@media (max-width: 768px) {
    .your-module-widget {
        padding: 0.5rem;
    }
}
JavaScript Features
// Module namespace
const YourModule = {
    init: function() {
        this.setupForms();
        this.setupWidgets();
    },
    
    setupForms: function() {
        // Form validation
        // AJAX submissions
        // User feedback
    }
};

document.addEventListener('DOMContentLoaded', 
    () => YourModule.init()
);
Pro Tips
  • Use CSS custom properties for easy theming
  • Implement progressive enhancement (works without JS)
  • Follow Bootstrap 5 conventions for consistency
  • Optimize for mobile-first responsive design

7. Admin Interface

Create professional admin interfaces for your module settings and management:

Settings Form
<form method="post" class="settings-form">
    <div class="mb-3">
        <label class="form-label">Enable Module</label>
        <div class="form-check form-switch">
            <input type="checkbox" 
                   class="form-check-input" 
                   name="enabled">
        </div>
    </div>
    
    <button type="submit" 
            class="btn btn-primary">
        Save Settings
    </button>
</form>
Dashboard Stats
public function renderAdminDashboard() {
    $stats = $this->getStats();
    
    echo '<div class="row">';
    echo '<div class="col-md-3">';
    echo '<div class="card text-center">';
    echo '<div class="card-body">';
    echo '<h3>' . $stats['total'] . '</h3>';
    echo '<p>Total Items</p>';
    echo '</div></div></div>';
    echo '</div>';
}
Admin Best Practices
User Experience
  • Clear navigation
  • Helpful descriptions
  • Success/error messages
  • Consistent styling
Security
  • CSRF protection
  • Input validation
  • Permission checks
  • XSS prevention
Performance
  • Efficient queries
  • Proper indexing
  • Caching strategies
  • Lazy loading

8. Best Practices

✅ Do This
Use namespaces
Avoid naming conflicts with other modules
Validate all inputs
Sanitize and validate user data
Handle errors gracefully
Use try-catch blocks and log errors
Use simple settings
Store settings as basic key-value pairs
Follow coding standards
PSR-12 compliance for PHP code
❌ Avoid This
Complex settings objects
Causes "[object Object]" in admin UI
Global variables
Can cause conflicts and bugs
Direct database queries
Use prepared statements always
Hardcoded paths
Use relative paths and constants
Ignoring permissions
Always check user capabilities
Security Checklist
  • ✅ Escape all output
  • ✅ Validate all input
  • ✅ Use prepared statements
  • ✅ Implement CSRF protection
  • ✅ Check user permissions
  • ✅ Sanitize file uploads
  • ✅ Log security events
  • ✅ Use HTTPS for sensitive data

9. Troubleshooting

Problem: Admin settings display "[object Object]" instead of form controls.
Solution: Use simple values in your settings, not complex objects:
// ❌ Wrong
"enabled": {"type": "boolean", "default": true}

// ✅ Correct  
"enabled": true

Check:
  • File permissions (755 for directories, 644 for files)
  • Namespace matches directory structure
  • module.json syntax is valid
  • Module is enabled in database
  • No PHP syntax errors (check error logs)

Common causes:
  • Missing database permissions
  • Table name conflicts
  • Invalid SQL syntax
  • Character set issues
Fix: Check error logs and verify database permissions. Use utf8mb4 charset.

Check:
  • File paths are correct
  • Web server can serve static files
  • No 404 errors in browser console
  • Assets are loaded conditionally
Debug: View page source and check asset URLs.

10. Deployment

Packaging Your Module
  1. Test thoroughly in development
  2. Update version numbers
  3. Create ZIP archive of module folder
  4. Include documentation
  5. Test installation on clean system
ZIP Structure:
your-module-v1.0.0.zip
└── your_module/
    ├── YourModule.php
    ├── install.php
    ├── module.json
    └── ...
Installation Methods
Manual Installation
  1. Upload files to modules/ directory
  2. Run php install.php
  3. Enable in admin panel
Admin Panel
  1. Upload ZIP via admin interface
  2. Auto-extraction and installation
  3. Immediate availability
Pre-Deployment Checklist
  • ✅ All features tested
  • ✅ No PHP errors or warnings
  • ✅ Database queries optimized
  • ✅ Cross-browser compatibility
  • ✅ Mobile responsiveness
  • ✅ Security audit completed
  • ✅ Documentation updated
  • ✅ Version numbers incremented

Ready to Build Your Module?

Download our complete example module and start building immediately

Need Help?

Join our community or get professional support for your PhPstrap module development.