PHPackages                             roy404/utilities - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. roy404/utilities

ActiveLibrary[Caching](/categories/caching)

roy404/utilities
================

A comprehensive collection of PHP utilities including Carbon, Logger, Storage, RateLimiter, Cache, and Session Handler, and more designed to enhance productivity and simplify development.

9.1.6(5mo ago)1546[1 issues](https://github.com/roycanales17/Web-Utilities/issues)1MITPHPPHP ^8.1

Since Jan 19Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/roycanales17/Web-Utilities)[ Packagist](https://packagist.org/packages/roy404/utilities)[ RSS](/packages/roy404-utilities/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (394)Used By (1)

PHP Utilities Library
=====================

[](#php-utilities-library)

A comprehensive collection of essential **PHP utilities** designed to streamline development and enhance productivity. This library includes versatile tools for common tasks, offering a robust foundation for building efficient and maintainable applications.

---

⚙️ Installation
---------------

[](#️-installation)

```
composer require roy404/utilities
```

Then include the autoloader in your project entry file (e.g., index.php):

```
require_once 'autoload.php';
```

---

🚀 Features
----------

[](#-features)

This library includes a range of utility classes to handle common development needs:

- [**Cache**](#cache) — Simplified caching interface for fast, temporary storage.
- [**Carbon**](#carbon) — Simplified date and time manipulation.
- [**Environment**](#environment) — Easy access to environment-based settings.
- [**Logger**](#logger) — Lightweight logging system to track events, errors, and debug output.
- [**Mail**](#mail) — Utility for sending emails with flexible transport options.
- [**Storage**](#storage) — Easy-to-use file storage and management with local and cloud support (e.g., AWS S3).
- [**RateLimiter**](#ratelimiter) — Control access frequency and throttle requests effectively.
- [**Server**](#server) — Useful helpers for interacting with server and request data.
- [**Session**](#session) — Streamlined session management and flash messaging.
- [**StreamWire**](#stream-wire) - Build interactive, stateful PHP components with real-time updates — no JavaScript required.

This library is modular, lightweight, and optimized for seamless integration into your PHP projects.
Whether you're working on a small application or a large-scale system, **PHP Utilities Library** provides the tools you need to get the job done efficiently.

---

🧩 Feature Documentation
-----------------------

[](#-feature-documentation)

Cache
-----

[](#cache)

A lightweight caching system that improves performance and reduces database overhead. It provides a unified interface for **Redis** and **Memcached** drivers, allowing you to store, retrieve, and manage cached data efficiently.

**Usage Example:**

```
use App\Utilities\Cache;
use App\Utilities\Blueprints\CacheDriver;

// ------------------------------------------------------
// STEP 1: Configure the Cache Driver
// ------------------------------------------------------

// Supported drivers: Redis | Memcached
$driver = CacheDriver::Memcached->value;
$host = 'memcached';
$port = '11211';

// Initialize cache connection
Cache::configure($driver, $host, $port);

// ------------------------------------------------------
// STEP 2: Basic Cache Operations
// ------------------------------------------------------

// Store an item in cache for 3 minutes (60 * 3 seconds)
Cache::set('key', 'value', 60 * 3);

// Retrieve an item from cache (returns 'default' if not found)
$value = Cache::get('key', 'default');

// Check if a cache key exists
if (Cache::has('key')) {
    echo "Cache key exists!";
}

// Delete a specific cache key
Cache::delete('key');

// Clear all cache entries (use carefully in production)
Cache::clear();

// ------------------------------------------------------
// STEP 3: Advanced Usage
// ------------------------------------------------------

// Get the expiration timestamp of a cache entry
$expiration = Cache::getExpiration('key');

// Retrieve cached value if exists, otherwise compute and cache it
$result = Cache::remember('user_profile', function () {
    // Example: Fetch data from a slow API or database
    return ['name' => 'Roy', 'role' => 'Admin'];
}, 60 * 3);

// ------------------------------------------------------
// Example Output
// ------------------------------------------------------
var_dump($value, $expiration, $result);
```

### Remarks

[](#remarks)

- **Supported Drivers:**
    - **Redis** - Recommended for high-performance, distributed caching.
    - **Memcached** - Great for lightweight, in-memory key-value caching.
- **Performance Tip:**
     Cache frequently accessed or computationally expensive data (e.g., database queries, API calls).
- **Best Practice:**
     Configure your cache driver once (typically on application boot) before any cache operations.
- **Safe Clearing:**
     Avoid using `Cache::clear()` in production unless you intend to reset the entire cache.
- **Expiration Management:**
     Use shorter durations for frequently changing data and longer durations for stable or rarely updated information.

---

Carbon
------

[](#carbon)

A lightweight utility class for date and time manipulation, built on top of PHP’s native `DateTime`. It provides an expressive and consistent API for handling time operations such as adding days, comparing dates, and formatting timestamps.

**Usage Example:**

```
use App\Utilities\Carbon;

// ------------------------------------------------------
// STEP 1: Working with the Current Date and Time
// ------------------------------------------------------

// Get the current date and time
$now = Carbon::now();

// Get today's date (time set to 00:00:00)
$today = Carbon::today();

// ------------------------------------------------------
// STEP 2: Date Manipulation
// ------------------------------------------------------

// Add days to the current date
$futureDate = Carbon::addDays(1);

// Subtract days from the current date
$pastDate = Carbon::subtractDays(2);

// ------------------------------------------------------
// STEP 3: Date Comparison
// ------------------------------------------------------

// Check if a given date is in the future
$isFuture = Carbon::isFuture('2025-12-25');

// Check if a given date is in the past
$isPast = Carbon::isPast('2023-01-01');

// Calculate the difference in days between two dates
$daysBetween = Carbon::diffInDays('2025-01-01', '2025-02-01');

// ------------------------------------------------------
// STEP 4: Formatting and Parsing
// ------------------------------------------------------

// Format the current date and time
$formatted = Carbon::format('Y-m-d H:i:s');

// Parse a string date into a Carbon instance
$parsedDate = Carbon::parse('2025-10-17 14:30:00');

// ------------------------------------------------------
// Example Output
// ------------------------------------------------------
var_dump($now, $today, $futureDate, $pastDate, $isFuture, $isPast, $daysBetween, $formatted, $parsedDate);
```

### Remarks

[](#remarks-1)

- **Immutable Operations:**
     Each Carbon operation returns a new instance, leaving the original date unchanged.
- **Flexible Input:**
     You can pass any valid date string or timestamp to Carbon methods.
- **Readable Syntax:** Carbon’s method naming makes date manipulation expressive and intuitive (e.g., `addDays`, `diffInDays`).
- **Timezone-Aware:**
     Automatically respects PHP’s timezone settings (`date_default_timezone_set`).

---

Environment
-----------

[](#environment)

Provides a simple and consistent way to **load** and **access** configuration values\*\* across your application.

This utility reads environment variables, ensuring that settings are centralized, easy to maintain, and environment-aware.

**Usage Example:**

```
// Get an environment value by key.
// Returns 'Framework' if 'APP_NAME' is not set.
$appName = env('APP_NAME', 'Framework');

// Retrieve a database setting (example)
$dbHost = env('DB_HOST', 'localhost');
```

### Remarks

[](#remarks-2)

- **Centralized Management:**
     Keeps environment and application settings organized in one place.
- **Safe Defaults:**
     The second argument of `env()` provides a fallback when a key is missing.
- **Runtime Flexibility:**
     You can modify configurations on the fly, useful for testing or dynamic environments.
- **Environment Integration:**
     Works seamlessly with `.env` or array-based configuration files.
- **Best Practice:**
     Avoid hardcoding credentials or secrets — store them in environment variables instead.

---

Logger
------

[](#logger)

A lightweight and flexible logging system for `application-level event tracking`, `debugging`, and `error reporting`.

It allows you to record messages of different severity levels and automatically store them in log files for later analysis.

**Usage Example:**

```
use App\Utilities\Logger;

// ------------------------------------------------------
// STEP 1: Initialize the Logger
// ------------------------------------------------------
// Parameters:
// 1️⃣ Log filename (optional, default: 'app.log')
// 2️⃣ Directory path where logs are stored

$logger = new Logger('app.log', 'storage/private/logs');

// ------------------------------------------------------
// STEP 2: Logging Different Message Types
// ------------------------------------------------------

// Debug → For development and diagnostic details
$logger->debug('Debug message', [
    'context1' => 'value1',
    'context2' => 'value2'
]);

// Info → General runtime events
$logger->info('User successfully logged in.');

// Warning → Non-critical issue that may need attention
$logger->warning('Memory usage nearing threshold.');

// Error → Exception or failed operation
$logger->error('Database connection failed.', [
    'file' => __FILE__,
    'line' => __LINE__,
    'context' => [
        'user_id' => 42,
        'endpoint' => '/login'
        + and more...
    ]
]);
```

### **Example Error Trace Output**

[](#example-error-trace-output)

When an unhandled exception occurs, the logger automatically generates a detailed trace like the example below:

```
🚨 [ERROR] [2025-10-17 00:10:46]

Type     : ERROR
Message  : Call to undefined function asdasds()
File     : /var/www/html/routes/web.php
Line     : 16

🌐 Context:
url           : /
method        : GET
ip            : 172.19.0.1
host          : localhost:8000
protocol      : HTTP/1.1
secure        : false
is_ajax       : false
request_id    : 1d8ba2d8ee4b967f
response_code : 200
request_time  : 1760659846 [2025-10-17 00:10:46]
client_port   : 64666
server_ip     : 172.19.0.9
referer       : No Referer
content_type  : Unknown Content-Type
session_id    : 52a10629187821c8402284734b3b19bc

🔍 Trace:
#0 /var/www/html/routes/src/Scheme/Facade.php(148): require()
#1 /var/www/html/routes/src/Scheme/Facade.php(45): App\Routes\Scheme\Facade->loadRoutes(true)
#2 /var/www/html/routes/src/Route.php(48): App\Routes\Scheme\Facade->__construct('', Array, Array, '/var/www/html/r...', Array, '', true, 'localhost')
#3 /var/www/html/utilities/core/Application.php(101): App\Routes\Route::configure('/var/www/html/r...', Array, '', 'localhost')
#4 /var/www/html/app/Bootstrap.php(8): App\Bootstrap\Application->run(Object(Closure))
#5 /var/www/html/public/index.php(18): require_once('/var/www/html/a...')
#6 {main}
-----------------------------------------------

```

### Remarks

[](#remarks-3)

- **Log Levels:**
    - 🐞 `debug` -&gt; Detailed system info for development
    - ℹ️ `info` -&gt; Standard runtime events
    - ⚠️ `warning` -&gt; Non-breaking but important notices
    - 🚨 `error` -&gt; Exceptions, failures, or fatal errors
- **Structured &amp; Human-Readable:**
     Each log entry is formatted with clear sections for `Message`, `Context`, and `Trace`.
- **Thread-Safe Writes:**
     Uses `LOCK_EX` to prevent race conditions during concurrent writes.
- **Environment Integration:**
     Works seamlessly with `.env` or array-based configuration files.
- **Customizable Output:**
     You can adjust directory, file name, or (optionally) verbosity level for different environments.

---

Mail
----

[](#mail)

A simple and extensible email utility that supports multiple transport options such as **SMTP**, **TLS**, and **custom mail drivers**.

It allows you to send emails directly or by defining reusable **Mailable** classes for clean and maintainable implementations.

**Configuration:**

```
use App\Utilities\Mail;

// ------------------------------------------------------
// STEP 1: Configure the mail transport
// ------------------------------------------------------
// Parameters:
// 1️⃣ Hostname
// 2️⃣ Port
// 3️⃣ Encryption type (tls | ssl | none)
// 4️⃣ Transport driver (smtp, sendmail, etc.)
// 5️⃣ Credentials (username/password)

Mail::configure('smtp.mailserver.com', 587, 'tls', 'smtp', [
    'username' => 'admin',
    'password' => 'admin123',
]);
```

**Basic Usage:**

```
use App\Utilities\Mail;

// ------------------------------------------------------
// STEP 2: Compose and send an email
// ------------------------------------------------------

Mail::to(['user@example.com', 'support@example.com'])
    ->from('noreply@example.com')
    ->subject('Welcome to our platform!')
    ->body('Hello!Thanks for joining us.')
    ->contentType('text/html')
    ->cc('manager@example.com')
    ->bcc('audit@example.com')
    ->replyTo('support@example.com')
    ->attach('This is the content', 'attachment.pdf') // Optional
    ->embedImage(base_path('/public/favicon.ico'), 'inlineImage') // Optional
    ->charset('UTF-8')
    ->header('X-Mailer', 'PHP Utilities Mailer')
    ->send();
```

Notes:

- Supports HTML and plain text bodies.
- `to()`, `cc()`, and `bcc()` accept a string or array of recipients.
- `attach()` and `embedImage()` allow file attachments and inline images.
- Automatically handles MIME type, boundary, and encoding.

**Using a Mailable Class:**
 For more structured and reusable emails, extend the `Mailable` handler.

```
namespace Mails;

use App\Utilities\Handler\Mailable;

class Test extends Mailable
{
    public array $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function send(): bool
    {
        // ------------------------------------------------------
        // STEP 1: Define the Blade template and data to inject
        // ------------------------------------------------------
        // 'template' refers to /views/template.blade.php

        // STEP 2: Build and send the email immediately
        return $this->view('template', $this->data)->build();
    }
}
```

Then call it like this:

```
use App\Utilities\Mail;
use Mails\Test;

Mail::mail(new Test([
    'name' => 'Roy'
]));
```

**Example Blade Template:**
 Your email view should be located at `/views/template.blade.php`:

```

    Hi {{ $name }},
    Welcome to our PHP Utilities Library!

```

### Remarks

[](#remarks-4)

- **Flexible Transport Layer:** Works with SMTP, Sendmail, or custom adapters.
- **Template Rendering:** Uses Blade for dynamic and clean templating.
- **Chainable API:** Intuitive builder-style syntax for composing messages.
- **Attachment &amp; Embedding:** Easily attach files or embed inline images.
- **Reusable Mailables:** Great for larger projects or multiple email templates.
- **Production Safe:** Credentials and host details can be loaded from configuration or environment variables.

---

Storage
-------

[](#storage)

A unified file storage and management system supporting local and cloud drivers (e.g., **AWS S3**).
 It provides a simple, fluent interface for reading, writing, and managing files and directories.

**Configuration**
 Before using, configure the default storage path:

```
use App\Utilities\Storage;

// Set default storage directory (optional)
// Default: 'storage'
Storage::configure('storage');
```

You can also define multiple disks like `local` or `s3`, each referring to different storage handlers.

**Basic Usage:**

```
use App\Utilities\Storage;

// Store a file
Storage::disk('local')->put('public/file.txt', 'File contents');

// Retrieve file content
$content = Storage::disk('local')->get('public/file.txt');

// Check existence
if (Storage::disk('local')->exists('public/file.txt')) {
    echo 'File exists!';
}

// Delete a file
Storage::disk('local')->delete('public/file.txt');
```

### **Common Operations:**

[](#common-operations)

1. **Write Files**
     Writes content to a file. Automatically creates the file if it doesn’t exist.

```
App\Utilities\Storage::put('notes/todo.txt', 'Buy groceries');
```

2. **Read Files**
     Returns file content as a string or `null` if the file doesn’t exist.

```
$content = App\Utilities\Storage::get('notes/todo.txt');
```

3. **Check Existence**

```
if (App\Utilities\Storage::exists('notes/todo.txt')) {
    // Do something
}
```

4. **Delete Files**
     Removes the file if it exists.

```
App\Utilities\Storage::delete('notes/todo.txt');
```

### **Copy or Move Files:**

[](#copy-or-move-files)

```
use App\Utilities\Storage;

// Copy file
Storage::copy('old/file.txt', 'backup/file.txt');

// Move file
Storage::move('temp/file.txt', 'final/file.txt');
```

### File Info

[](#file-info)

```
use App\Utilities\Storage;

$size = Storage::size('data/report.csv'); // in bytes
$lastModified = Storage::lastModified('data/report.csv'); // timestamp
```

### URLs

[](#urls)

```
use App\Utilities\Storage;

// returns a permanent public link.
$url = Storage::url('public/image.png');

// generates a signed temporary URL valid until expiration.
$tempUrl = Storage::temporaryUrl('public/image.png', new DateTime('+1 hour'));
```

### Directory Management

[](#directory-management)

```
use App\Utilities\Storage;

// List all files in directory
$files = Storage::allFiles('images');

// List all directories
$directories = Storage::allDirectories('images');

// Create new directory
Storage::makeDirectory('uploads/new-folder');

// Delete a directory
Storage::deleteDirectory('uploads/old-folder');
```

### Working with Multiple Disks

[](#working-with-multiple-disks)

```
use App\Utilities\Storage;

// Local storage
Storage::disk('local')->put('local.txt', 'Stored locally');

// S3 storage
Storage::disk('s3')->put('cloud.txt', 'Stored in the cloud');
```

### Example: Private File with Temporary Access

[](#example-private-file-with-temporary-access)

```
use App\Utilities\Storage;
use DateTime;

// 1. Generate temporary URL valid for 10 minutes
$tempUrl = Storage::temporaryUrl('private/report.pdf', new DateTime('+10 minutes'));

// 2. User accesses link (validation + secure serve)
if (Storage::validateTemporaryUrl($_GET['url'])) {
    return Storage::serveTemporaryFile($_GET['url']);
}

echo 'Link expired or invalid.';
```

---

RateLimiter
-----------

[](#ratelimiter)

The `RateLimiter` provides a simple and efficient way to throttle actions and prevent abuse or brute-force attacks by limiting how many times a specific action can be performed within a given time frame.

It uses a cache-based mechanism (via the `Cache` utility) to track request counts per user/IP and automatically resets limits after the defined decay period.

### Concept

[](#concept)

Each limit is tracked by a unique key (e.g., `login`, `password_reset`, or API endpoint name) combined with the user's IP address.
 This allows you to independently control rate limits for different operations or users.

**Usage Example:**

```
use App\Utilities\RateLimiter;

// Allow up to 5 login attempts every 60 seconds
if (!RateLimiter::attempt('login', 5, 60)) {
    echo "⛔ Too many login attempts. Please try again later.";
    exit;
}

echo "✅ Login attempt allowed.";
```

`attempt($key, $limit, $decayRate)`

- `$key` - unique action name
- `$limit` - max attempts allowed
- `$decayRate` - window in seconds before reset

**Time-Based Shortcuts**
 You can also apply limits using convenient, readable helpers:

```
use App\Utilities\RateLimiter;

// Allow 3 attempts per minute
RateLimiter::perMinute('api_request', 3);

// Allow 100 operations per hour
RateLimiter::perHour('user_uploads', 100);

// Allow 1000 requests per day
RateLimiter::perDay('daily_report', 1000);

// Allow 5000 actions per month
RateLimiter::perMonth('monthly_summary', 5000);
```

Each helper internally calls `attempt()` with the appropriate decay window.

### How It Works

[](#how-it-works)

1. The limiter identifies the user by IP (via `Server::IPAddress()`).
2. It checks the cache for the remaining number of allowed attempts.
3. If none exist, it creates a new entry with the configured limit and expiration.
4. Each valid attempt **decrements the counter** until it reaches zero.
5. Once the window expires, the counter automatically resets.

---

Server
------

[](#server)

Provides helper methods to interact with the server and request environment data.

This utility offers an abstraction layer over PHP’s `$_SERVER` global, ensuring safer access and cleaner syntax for retrieving request information.

### Features

[](#features)

- Retrieves client and server IPs
- Detects secure (HTTPS) connections
- Identifies AJAX requests
- Provides headers and environment metadata
- Generates a unique request ID if missing

**Usage Example:**

```
use App\Utilities\Server;

$ip         = Server::IPAddress();
$userAgent  = Server::userAgent();
$method     = Server::requestMethod();
$isSecure   = Server::isSecureConnection();
$isAjax     = Server::isAjaxRequest();
$requestId  = Server::requestId();

echo "Client IP: {$ip}";
echo "User Agent: {$userAgent}";
```

### Available Methods

[](#available-methods)

MethodDescription`IPAddress()`Gets the client’s IP address, checking proxy headers like `X-Forwarded-For`.`userAgent()`Retrieves the client’s User-Agent string.`hostName()`Returns the requested host name (domain).`requestMethod()`Gets the HTTP request method (`GET`, `POST`, etc.).`requestURI()`Gets the full request URI path.`referer()`Returns the HTTP referer or `"No Referer"` if unavailable.`queryString()`Retrieves the request’s query string parameters.`isSecureConnection()`Checks if the connection uses HTTPS.`clientPort()`Gets the client’s port number.`serverIPAddress()`Retrieves the server’s IP address.`requestTime()`Returns the timestamp of the request.`isAjaxRequest()`Detects if the current request was made via AJAX.`contentType()`Gets the request’s `Content-Type` header.`accept()`Retrieves the `Accept` header value.`protocol()`Returns the HTTP protocol version (`HTTP/1.1`, `HTTP/2`, etc.).`requestId()`Gets the `X-Request-ID` header or generates one if missing.---

Session
-------

[](#session)

Provides a simple and consistent interface for managing PHP sessions, including **flash data**, **custom handlers**, and **configurable drivers**.

**Supports:**

- File-based sessions
- Database-based sessions
- (Future) Redis-based sessions
- Flash messages (temporary session data)
- Session regeneration and cleanup

**Usage Example:**

```
use App\Utilities\Session;

// Start or configure the session
Session::configure([
    'driver' => 'file',
    'session' => [
        'lifetime' => 120,
        'path' => '/',
        'http_only' => true,
        'same_site' => 'lax',
    ],
]);

Session::start();

// Store and retrieve session data
Session::set('user', 'Roy');
echo Session::get('user'); // Outputs: Roy

// Flash message (available for one request)
Session::flash('success', 'Profile updated successfully!');

// Retrieve flash data later
$message = Session::flash('success'); // "Profile updated successfully!"
```

### Available Methods

[](#available-methods-1)

MethodDescription`configure(array $config)`Configures session settings such as driver, lifetime, and cookie parameters. Supports file and database handlers.`start()`Starts the session if it’s not already active.`started()`Checks whether a session is currently active.`set(string $key, mixed $value)`Stores a value in the session under the specified key.`get(string $key, mixed $default = false)`Retrieves a value from the session or returns a default if not found.`has(string $key)`Determines if a session key exists.`remove(string $key)`Removes a specific key from the session.`flash(string $key, mixed $value = false)`Sets or retrieves temporary “flash” data that persists for one request only.`destroy()`Completely destroys the session and clears all data.`regenerate(bool $deleteOldSession = true)`Regenerates the session ID for improved security.Stream-Wire
-----------

[](#stream-wire)

Stream-Wire enables you to build dynamic, interactive PHP components without writing JavaScript. It bridges backend and frontend communication automatically, allowing components to update and react to user interactions seamlessly — using pure **PHP**.

### Installation &amp; Setup

[](#installation--setup)

1. **Publish Required Assets:**```
    php artisan public:stream
    ```

    This publishes all necessary JavaScript and CSS files to: ```
    /public/libraries/streamdom/
    ```
2. **Include Assets in Your Layout**
    In your main layout (e.g., `layout.blade.php`): ```

    ```

    Or in your stylesheet: ```
    @import "/libraries/streamdom/stream.css";
    ```

### Creating a Component

[](#creating-a-component)

Generate a new component using Artisan:

```
php artisan make:component Counter
```

This will create:

FileDescription`./components/Counter.php`Contains the backend logic and lifecycle methods.`./views/components/counter.blade.php`Defines the frontend markup and data bindings.### Component Lifecycle

[](#component-lifecycle)

Each Stream-Wire component extends the base class:

```
use App\Utilities\Handler\Component;
```

Your component may define any of the following methods:

MethodPurpose**init()**Initializes internal state or dependencies. Called when the component is first loaded.**verify(): bool***(Optional)* Perform validation or pre-render checks.**identifier(): string**Must be `static`. Used by the frontend to reference this component.**loader(): string**Returns temporary content shown while the component is processing.**redirect(string $path)**Performs an AJAX-based redirect.**render(): array**Renders the final component view. Must return `$this->compile([...])`.### Example 1 — Simple Counter Component

[](#example-1--simple-counter-component)

`./components/Counter.php`

```
namespace Components\Counter;

use App\Utilities\Handler\Component;

class Counter extends Component
{
    public string $name = "Robroy";

    /** @see ./views/components/counter.blade.php */
    public function render(): array
    {
        return $this->compile([
            'name' => $this->name,
        ]);
    }
}
```

`./views/components/counter.blade.php`

```
@php
use Components\Counter;
/**
 * This file is rendered by:
 * @see Components\Counter::render()
 */
@endphp

        Your Name is {{ $name }}

        Submit

        Submit 2

        Trigger Another Component

```

### Usage in Blade or PHP Views

[](#usage-in-blade-or-php-views)

To render a component:

```
$component = Components\Counter::class;
$init_params = ['name' => 'Robroy'];
$asynchronous = true;

echo stream($component, $init_params, $asynchronous);
```

#### Parameters

[](#parameters)

ParameterTypeDescription**$component**`string`Fully-qualified class name of the component.**$init\_params**`array`Optional initial data to assign to the component’s public properties during initialization.**$asynchronous**`bool`Determines whether the component should load asynchronously. When set to `true`, a loader or skeleton placeholder is rendered immediately, and the actual component is loaded in the background—allowing other components or page processes to continue without waiting.### Available Frontend Directives

[](#available-frontend-directives)

DirectiveDescription`wire:click="method()"`Calls a backend method when clicked.`wire:model="property"`Binds an input field to a backend property (two-way binding).`wire:submit="method()"`Handles form submissions via AJAX.`wire:loading`Displays content while waiting for backend response.#### Key-based Directives

[](#key-based-directives)

DirectiveDescription`wire:keydown.enter`Triggers on Enter key press.`wire:keydown.escape`Triggers on Escape key press.`wire:keydown.backspace`Triggers on Backspace.`wire:keydown.tab`Triggers on Tab.`wire:keydown.delete`Triggers on Delete.`wire:keydown.keypress`Fires when any key is pressed.#### Each of the above supports chained modifiers:

[](#each-of-the-above-supports-chained-modifiers)

ModifierDescription`.clear`Clears the input value after execution.`.refresh`Forces a full component refresh.`.rebind`Re-runs scripts inside the rendered HTML.`.prevent`Equivalent to `e.preventDefault()`.`.100ms`, `.300ms`, `.500ms`, +... `1000ms`.Adds delay before executing the action.#### Loader Directive

[](#loader-directive)

The `wire:loader` directive executes before a request is made.

**Example:**

```

    Saving...

```

**Modifiers**

ModifierDescription`.classList.add="..."`Adds a class while loading.`.classList.add.retain="..."`Retains class after completion.`.classList.remove="..."`Removes a class while loading.`.style="..."`Adds inline style during request.`.style.retain="..."`Keeps style after request completes.`.attr="..."`Adds an attribute during request.`.attr.retain="..."`Retains the attribute after request.### Advanced Features

[](#advanced-features)

**Execute Methods Manually**

You can call backend methods directly using the helper:

```
stream()->execute([Counter::class, 'render']);
```

**Target Other Components**To execute a method on a different component:

```
wire:click="{!! stream()->target([Counter2::class, 'render']) !!}"

```

### Behavior Summary

[](#behavior-summary)

Stream-Wire automatically synchronizes backend data and frontend state:

- No page reloads.
- No manual JavaScript.
- Automatic partial updates.
- Built-in loading feedback.

Write expressive PHP, and let Stream-Wire handle the browser updates.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance51

Moderate activity, may be stable

Popularity14

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

393

Last Release

174d ago

Major Versions

v5.5.9 → v6.0.02025-09-15

v2.6.0 → v6.6.12025-10-21

v6.6.9 → v7.0.02025-10-22

7.5.5 → 8.0.02025-10-27

8.9.9 → 9.0.02025-11-22

PHP version history (2 changes)v1.0.1PHP ^8.0

v1.4.0PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/542567e23f273798a0a4a752804c792654fe6c3753b53752b1d00b7eff2b8b11?d=identicon)[roycanales](/maintainers/roycanales)

---

Top Contributors

[![roycanales17](https://avatars.githubusercontent.com/u/62797701?v=4)](https://github.com/roycanales17 "roycanales17 (693 commits)")

---

Tags

cachecarbonloggerratelimitersessionstoragephpcompiler

### Embed Badge

![Health badge](/badges/roy404-utilities/health.svg)

```
[![Health](https://phpackages.com/badges/roy404-utilities/health.svg)](https://phpackages.com/packages/roy404-utilities)
```

###  Alternatives

[awssat/laravel-visits

Laravel Redis visits counter for Eloquent models

975163.6k2](/packages/awssat-laravel-visits)[swayok/alternative-laravel-cache

Replacements for Laravel's redis and file cache stores that properly implement tagging idea. Powered by cache pool implementations provided by http://www.php-cache.com/

202541.1k6](/packages/swayok-alternative-laravel-cache)[swoft/redis

swoft redis component

12168.4k16](/packages/swoft-redis)[eftec/cacheone

A Cache library with minimum dependency

103.5k4](/packages/eftec-cacheone)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
