PHP Jquery Component Library

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/preciouslyson/lizulu

1.0.0 2025-12-21 10:12 UTC

This package is auto-updated.

Last update: 2025-12-21 10:21:40 UTC


README

Lizulu - PHP Jquery Component Library

A comprehensive PHP library for generating jQuery JavaScript code programmatically. This library provides a structured, object-oriented approach to creating jQuery scripts, AJAX requests, DOM manipulation, event handling, and form validation from PHP.

Table of Contents

  • #features
  • #installation
  • #documentation
  • #license
  • #Support
  • #Acknowledgments

Features · Programmatic jQuery Generation: Write jQuery code using PHP objects and methods · Component-Based Architecture: Modular components for AJAX, DOM, Events, and Validation · Type-Safe: PHP type hints and validation · AJAX Support: Full-featured AJAX request building with CSRF protection · DOM Manipulation: Create and manipulate DOM elements programmatically · Event Handling: Comprehensive event system with namespacing and delegation · Form Validation: Client-side validation with custom rules and live validation · Script Building: Advanced script building with minification and organization

Installation Requirements

· PHP 7.4 or higher · Composer · jQuery (loaded in your frontend)

Install via Composer

composer require preciouslyson/lizulu

Documentation

<?php
use Mlangeni\Machinjiri\JS\JQueryLibrary;

// Initialize the library
$jquery = new JQueryLibrary();

// Basic AJAX request
$ajaxScript = $jquery->ajax()
    ->url('/api/data')
    ->type('POST')
    ->data(['id' => 123])
    ->success('function(response) { console.log(response); }')
    ->render();

echo $ajaxScript;

Outputs:

$.ajax({
    url: '/api/data',
    type: 'POST',
    data: {id: 123},
    success: function(response) { console.log(response); }
});

Configuration

Configure the library globally or per instance:

// Global configuration
JQueryLibrary::configure([
    'default_ajax_type' => 'POST',
    'ajax_timeout' => 30000,
    'csrf_token_name' => '_token',
    'debug' => true,
    'cache_ajax' => false
]);

// Or instance configuration
$jquery = new JQueryLibrary([
    'default_ajax_type' => 'GET',
    'debug' => false
]);

// Enable debug mode
JQueryLibrary::debug(true);

Components

  1. AJAX Component

Handle AJAX requests with a fluent interface:

// Simple GET request
$ajax = $jquery->ajax()
    ->url('/api/users')
    ->type('GET')
    ->dataType('json')
    ->success('function(data) { console.log(data); }')
    ->error('function(xhr) { alert("Error: " + xhr.statusText); }')
    ->render();

// Form submission with AJAX
$formAjax = $jquery->ajax()
    ->formData('#userForm')
    ->url('/submit')
    ->jsonResponse(
        'alert("Success!");',
        'alert("Error: " + response.error);'
    );

// File upload
$uploadScript = $jquery->helper('ajax')->upload(
    '#fileInput',
    '/upload',
    [
        'success' => 'function(response) { console.log("Uploaded:", response); }'
    ]
);
  1. DOM Component

DOM manipulation with method chaining:

// Create and manipulate elements
$dom = $jquery->dom('#container')
    ->click('alert("Clicked!");')
    ->chain('append', '<div>New Element</div>')
    ->chain('addClass', 'updated')
    ->execute();

// Dynamic content loading
$loader = $jquery->dom('#content')
    ->loadContent('/load-data', ['page' => 2]);

// Complex DOM operations
$complexDom = $jquery->dom()
    ->select('.items')
    ->click('$(this).toggleClass("active");')
    ->change('console.log("Changed:", $(this).val());')
    ->render();
  1. Event Component

Advanced event handling:

// Basic event binding
$events = $jquery->events()
    ->on('#button', 'click', 'alert("Clicked!");')
    ->delegate('#list', 'li', 'click', 'console.log("Item clicked");')
    ->one('#temp', 'click', 'alert("Only once!");');

// Keyboard events
$keyboard = $jquery->events()
    ->keyboard('body', 'Enter', 'submitForm();', false, false)
    ->keyboard('body', 's', 'saveForm();', true, false); // Ctrl+S

// Infinite scroll
$infinite = $jquery->events()
    ->infiniteScroll('#content', '/load-more', 'page', 200);

// Event bus for decoupled communication
$eventBus = $jquery->events()
    ->eventBus('app')
    ->namespaced('#component', 'click', 'namespace', 'app.emit("component.clicked");');

echo $events->render();
  1. Validator Component

Client-side form validation:

// Form validation setup
$validator = $jquery->validator()
    ->form('#registrationForm')
    ->required('username', 'Username is required')
    ->email('email', 'Please enter a valid email')
    ->min('password', 8, 'Password must be at least 8 characters')
    ->match('confirm_password', 'password', 'Passwords must match')
    ->regex('phone', '/^[0-9]{10}$/', 'Invalid phone number')
    ->live() // Enable live validation
    ->onSubmit('
        $.post("/register", $(this).serialize(), function(response) {
            if (response.success) {
                window.location.href = "/dashboard";
            }
        });
    ');

// Remote validation (AJAX)
$remoteValidator = $jquery->validator()
    ->form('#usernameForm')
    ->remote('username', '/check-username')
    ->render();

// Custom validation function
$validator->customValidator('uniqueEmail', '
    function(value) {
        var emails = ["existing@example.com", "test@example.com"];
        return emails.indexOf(value) === -1;
    }
')->custom('email', 'uniqueEmail', 'Email already exists');
  1. Script Builder

Advanced script building and organization:

use Mlangeni\Machinjiri\JS\Helpers\ScriptBuilder;

$builder = new ScriptBuilder([
    'minify' => false,
    'useStrict' => true,
    'wrapScriptTag' => true
]);

// Build complex scripts
$script = $builder
    ->var('appConfig', [
        'apiUrl' => '/api/v1',
        'debug' => true,
        'timeout' => 5000
    ], true)
    ->function('showNotification', ['message', 'type'], '
        var className = type === "error" ? "alert-danger" : "alert-success";
        var alert = $(\'<div class="alert \' + className + \'">\' + message + \'</div>\');
        $(".notifications").append(alert);
        setTimeout(function() { alert.fadeOut(); }, 3000);
    ')
    ->debounce('search', 300)
    ->throttle('resizeHandler', 250)
    ->ready('
        console.log("App initialized");
        $("#search").on("keyup", appDebounce(function() {
            performSearch($(this).val());
        }));
    ')
    ->ajaxSetup([
        'cache' => false,
        'headers' => [
            'X-Requested-With' => 'XMLHttpRequest'
        ]
    ])
    ->csrf('_token', 'your-csrf-token-here')
    ->build();

echo $script;

Helpers

JQueryHelper

// Create jQuery selectors
$selector = $jquery->helper('jquery')->selector('#element', '.context');

// Create plugin
$plugin = $jquery->helper('jquery')->plugin('tooltip', [
    'show' => '$(this).fadeIn();',
    'hide' => '$(this).fadeOut();'
]);

// Document ready
$ready = $jquery->helper('jquery')->ready('console.log("Document ready");');

DomHelper

// Create elements
$element = $jquery->helper('dom')->create('div', [
    'class' => 'alert',
    'data-id' => '123'
], 'Hello World');

// Append elements
$append = $jquery->helper('dom')->append('#parent', $element);

// CSS manipulation
$css = $jquery->helper('dom')->css('.item', [
    'color' => 'red',
    'font-weight' => 'bold'
]);

AjaxHelper

// Direct AJAX calls
$get = $jquery->helper('ajax')->get('/api/data', ['page' => 1]);
$post = $jquery->helper('ajax')->post('/submit', ['name' => 'John']);

// Form submission helper
$formSubmit = $jquery->helper('ajax')->submitForm('#myForm', [
    'success' => 'function(response) { console.log(response); }'
]);

// File upload helper
$upload = $jquery->helper('ajax')->upload('#file', '/upload');

Advanced Examples

Complete Application Setup

<?php
use Mlangeni\Machinjiri\JS\JQueryLibrary;

class ApplicationScripts
{
    private JQueryLibrary $jquery;
    
    public function __construct()
    {
        $this->jquery = new JQueryLibrary([
            'default_ajax_type' => 'POST',
            'csrf_token_name' => '_token',
            'debug' => APP_DEBUG
        ]);
    }
    
    public function buildDashboardScripts(): string
    {
        return $this->jquery->script(function($script) {
            // Initialize app
            $script->add('window.App = window.App || {};');
            
            // Load user data
            $script->add($this->jquery->ajax()
                ->url('/api/user/profile')
                ->type('GET')
                ->success('App.user = response;')
                ->render());
            
            // Real-time updates
            $script->add($this->jquery->events()
                ->infiniteScroll('#feed', '/api/feed/load', 'page', 100)
                ->render());
            
            // Form handling
            $script->add($this->jquery->validator()
                ->form('#settings-form')
                ->required('name')
                ->email('email')
                ->live()
                ->onSubmit('
                    $(this).ajaxSubmit({
                        success: function(response) {
                            showNotification("Settings saved!", "success");
                        }
                    });
                ')
                ->render());
            
            // Event bus for component communication
            $script->add($this->jquery->events()
                ->eventBus('dashboard')
                ->render());
        });
    }
}

CRUD Operations

class CrudManager
{
    public function getCrudScripts(string $endpoint): string
    {
        $jquery = new JQueryLibrary();
        
        // Create
        $createScript = $jquery->ajax()
            ->url("{$endpoint}/create")
            ->type('POST')
            ->formData('#createForm')
            ->jsonResponse(
                'location.reload();',
                'showError(response.errors);'
            );
        
        // Update
        $updateScript = $jquery->events()
            ->delegate('.edit-btn', 'click', '
                var id = $(this).data("id");
                $.get("' . $endpoint . '/" + id, function(data) {
                    populateEditForm(data);
                    $("#editModal").modal("show");
                });
            ');
        
        // Delete with confirmation
        $deleteScript = $jquery->events()
            ->delegate('.delete-btn', 'click', '
                if (confirm("Are you sure?")) {
                    var id = $(this).data("id");
                    $.ajax({
                        url: "' . $endpoint . '/" + id,
                        type: "DELETE",
                        success: function() {
                            $(this).closest("tr").fadeOut();
                        }
                    });
                }
            ');
        
        return $createScript . "\n" . $updateScript . "\n" . $deleteScript;
    }
}

SPA (Single Page Application) Router

class SPARouter
{
    public function buildRouter(): string
    {
        $jquery = new JQueryLibrary();
        
        return $jquery->script(function($script) use ($jquery) {
            $script->var('Router', [
                'routes' => [
                    '/' => 'home',
                    '/about' => 'about',
                    '/contact' => 'contact'
                ],
                'current' => null
            ], true);
            
            $script->function('navigate', ['path'], '
                if (Router.routes[path]) {
                    Router.current = path;
                    history.pushState({}, "", path);
                    loadPage(Router.routes[path]);
                }
            ');
            
            $script->add($jquery->events()
                ->delegate('a[data-route]', 'click', '
                    navigate($(this).data("route"));
                    return false;
                ')
                ->render());
            
            $script->add($jquery->ajax()
                ->url('/api/page/{page}')
                ->type('GET')
                ->data('{page: Router.routes[Router.current]}')
                ->success('$("#content").html(response.html);')
                ->render());
        });
    }
}

Best Practices

  1. Code Organization
// Organize by feature
class FeatureScripts
{
    private JQueryLibrary $jquery;
    
    public function __construct()
    {
        $this->jquery = new JQueryLibrary();
    }
    
    public function buildUserScripts(): string
    {
        $builder = new ScriptBuilder();
        
        // User-related scripts
        $builder->add($this->buildProfileScripts());
        $builder->add($this->buildSettingsScripts());
        $builder->add($this->buildNotificationsScripts());
        
        return $builder->build();
    }
    
    private function buildProfileScripts(): string
    {
        return $this->jquery->validator()
            ->form('#profileForm')
            // ... validation rules
            ->render();
    }
}
  1. Performance Optimization
// Use debouncing for search
$searchScript = $jquery->script(function($script) use ($jquery) {
    $script->debounce('search', 300);
    $script->add($jquery->events()
        ->on('#search', 'keyup', '
            appDebounce(function() {
                performSearch($("#search").val());
            });
        ')
        ->render());
});

// Lazy loading
$lazyLoad = $jquery->events()
    ->on('img[data-src]', 'load', '
        $(this).attr("src", $(this).data("src"));
    ');
  1. Security Considerations
// Always include CSRF protection
$jquery = new JQueryLibrary([
    'csrf_token_name' => '_token'
]);

// Or set it globally
JQueryLibrary::configure([
    'csrf_token_name' => 'csrf_token'
]);

// Validate all inputs
$validator = $jquery->validator()
    ->form('#secureForm')
    ->required('password')
    ->regex('password', '/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/')
    ->render();

API Reference

Main Classes

JQueryLibrary

· __construct(array $config = []) - Initialize with configuration · ajax(array $options = []): AjaxComponent - Create AJAX component · dom(string $selector = null): DomComponent - Create DOM component · events(): EventComponent - Create Event component · validator(array $rules = []): ValidatorComponent - Create Validator component · script(callable $callback = null): string - Generate complete script · helpers(): array - Get all helpers · helper(string $name): ?object - Get specific helper · static configure(array $config): void - Set global configuration · static debug(bool $enabled): void - Enable/disable debug mode

AjaxComponent

· url(string $url): self - Set URL · type(string $type): self - Set request type · data($data): self - Set request data · success(string $callback): self - Set success callback · error(string $callback): self - Set error callback · jsonResponse(string $success, string $error = null): string - JSON response handler · formData(string $selector): self - Handle form data · render(): string - Generate script

DomComponent

· select(string $selector): self - Set selector · click(string $handler): self - Add click event · chain(string $method, $arguments = null): self - Chain method · execute(): string - Execute chained methods · loadContent(string $url, array $params = []): string - Load content via AJAX

EventComponent

· on(string $selector, string $event, string $handler): self - Bind event · delegate(string $parent, string $selector, string $event, string $handler): self - Delegate event · namespaced(string $selector, string $event, string $namespace, string $handler): self - Namespaced event · keyboard(string $selector, string $key, string $handler, bool $ctrl = false, bool $shift = false): self - Keyboard event · infiniteScroll(string $container, string $url, string $dataKey = 'page', int $offset = 200): self - Infinite scroll · eventBus(string $busName = 'app'): self - Create event bus

ValidatorComponent

· form(string $selector): self - Set form selector · required(string $field, string $message = null): self - Required field · email(string $field, string $message = null): self - Email validation · min(string $field, int $min, string $message = null): self - Minimum length · max(string $field, int $max, string $message = null): self - Maximum length · live(bool $enabled = true): self - Enable live validation · onSubmit(string $handler): self - Set submit handler · remote(string $field, string $url, string $method = 'GET'): self - Remote validation

ScriptBuilder

· add(string $code): self - Add raw JavaScript · var(string $name, $value, bool $global = false): self - Add variable · function(string $name, array $params, string $body): self - Add function · debounce(string $name = 'debounce', int $delay = 300): self - Add debounce utility · throttle(string $name = 'throttle', int $limit = 300): self - Add throttle utility · ajaxSetup(array $options): self - Set AJAX defaults · csrf(string $tokenName = 'csrf_token', string $tokenValue = null): self - Add CSRF protection · build(): string - Build complete script

Testing

<?php
// Example test
use PHPUnit\Framework\TestCase;
use Mlangeni\Machinjiri\JS\JQueryLibrary;

class JQueryLibraryTest extends TestCase
{
    public function testAjaxRequestGeneration()
    {
        $jquery = new JQueryLibrary();
        $ajax = $jquery->ajax()
            ->url('/test')
            ->type('POST')
            ->data(['test' => 'value'])
            ->render();
        
        $this->assertStringContainsString('$.ajax', $ajax);
        $this->assertStringContainsString('url: \'/test\'', $ajax);
    }
    
    public function testDomManipulation()
    {
        $jquery = new JQueryLibrary();
        $dom = $jquery->dom('#test')
            ->click('console.log("clicked");')
            ->render();
        
        $this->assertStringContainsString('$(\'#test\')', $dom);
        $this->assertStringContainsString('.click', $dom);
    }
}

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

Development Setup

git clone https://github.com/preciouslyson/lizulu.git
cd lizulu
composer install

License

This library is open-source software licensed under the MIT license.

Support

· Documentation: GitHub Wiki · Issues: GitHub Issues · Discussions: GitHub Discussions

Acknowledgments

· jQuery team for the amazing library · All contributors who help improve this project

Built with ❤️ by the Mlangeni Group team