PHPackages                             zekiunal/unix - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. zekiunal/unix

ActiveProject[Utility &amp; Helpers](/categories/utility)

zekiunal/unix
=============

Example unix socket application

v1.0.1(1y ago)01PHPPHP ^8.4

Since Mar 31Pushed 1y ago1 watchersCompare

[ Source](https://github.com/zekiunal/unix)[ Packagist](https://packagist.org/packages/zekiunal/unix)[ RSS](/packages/zekiunal-unix/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (5)Used By (0)

PHP Unix Socket Microservices Architecture
==========================================

[](#php-unix-socket-microservices-architecture)

A powerful, lightweight microservices framework using PHP and Unix sockets for ultra-fast inter-service communication. This architecture provides a robust foundation for building modular, scalable applications with minimal overhead.

📋 Table of Contents
-------------------

[](#-table-of-contents)

- [Core Features](#core-features)
- [Architecture Overview](#architecture-overview)
- [Directory Structure](#directory-structure)
- [Core Components](#core-components)
- [Application Demos](#application-demos)
    - [Unix Socket App](#unix-socket-app)
    - [REST API App](#rest-api-app)
- [Communication Flow](#communication-flow)
- [Security](#security)
- [Performance Considerations](#performance-considerations)
- [Installation &amp; Setup](#installation--setup)
- [Usage Examples](#usage-examples)
- [Extending the Framework](#extending-the-framework)
- [Deployment with Docker](#deployment-with-docker)
- [Troubleshooting](#troubleshooting)

🚀 Core Features
---------------

[](#-core-features)

- **High-Performance Socket Communication**: Achieve microsecond-level latency between services
- **Process-based Isolation**: Each service runs in its own protected process environment
- **Robust Error Handling**: Comprehensive exception hierarchy with detailed logging
- **Clean Domain-Driven Design**: Separation of concerns with repository pattern
- **Dependency Injection**: PHP-DI integration for flexible service management
- **Signal Handling**: Graceful service shutdown and reload capabilities
- **Resource Monitoring**: Built-in metrics for performance analysis
- **Automatic Service Discovery**: Services locate and communicate with each other seamlessly
- **Dual Application Support**: Run as Unix Socket service or REST API

🏗️ Architecture Overview
------------------------

[](#️-architecture-overview)

The architecture follows clean hexagonal design principles with a focus on decoupling and testability:

 ```
graph TB
    subgraph "Application Layer"
        Unix["Unix Orchestrator"]
        Micro["Micro App"]
        Router["Router"]
    end

    subgraph "Domain Layer"
        UseCase["HandleMessageUseCase"]
        Repository["RouterRepositoryInterface"]
    end

    subgraph "Infrastructure Layer"
        RouterRepo["RouterRepository"]
        subgraph "Datasources"
            LibDatasource["Library\nRouterDatasource"]
            UnixDatasource["Unix\nRouterDatasource"]
        end
    end

    subgraph "Socket Layer"
        AbstractRequest["AbstractRequest"]
        SocketRequest["SocketRequest"]
        HttpRequest["HttpRequest"]
        Security["Security"]
        Config["Config"]
    end

    subgraph "Demo Applications"
        UnixApp["Unix Socket App"]
        RestApp["REST API App"]
    end

    %% Connections
    Unix --> AbstractRequest
    Unix --> Config
    Micro --> HttpRequest

    UnixApp --> Unix
    RestApp --> Micro

    SocketRequest --> AbstractRequest
    HttpRequest --> AbstractRequest

    UseCase --> Repository
    RouterRepo --> Repository
    RouterRepo --> LibDatasource
    RouterRepo --> UnixDatasource

    SocketRequest --> Security
    SocketRequest --> Config
    HttpRequest --> UseCase

    Router --> UseCase

    %% Styles
    classDef core fill:#f96,stroke:#333,stroke-width:2px;
    classDef domain fill:#bbf,stroke:#333,stroke-width:2px;
    classDef infra fill:#bfb,stroke:#333,stroke-width:2px;
    classDef socket fill:#fcf,stroke:#333,stroke-width:2px;
    classDef app fill:#ff9,stroke:#333,stroke-width:2px;

    class Unix,Micro,Router core;
    class UseCase,Repository domain;
    class RouterRepo,LibDatasource,UnixDatasource infra;
    class AbstractRequest,SocketRequest,HttpRequest,Security,Config socket;
    class UnixApp,RestApp app;
```

      Loading 📁 Directory Structure
---------------------

[](#-directory-structure)

```
library/unix/
├── client.php                 # Test client for socket connections
├── composer.json              # Dependency management
├── Dockerfile                 # Container configuration
├── rest-app/                  # HTTP API implementation
│   ├── Controllers/           # API controllers
│   ├── config/                # Application configuration
│   └── public/                # Application entry point
├── src/                       # Core framework code
│   ├── Application/           # Application layer
│   │   ├── Exception/         # Application exceptions
│   │   ├── Micro.php          # HTTP application core
│   │   ├── Router.php         # Request router
│   │   └── Unix.php           # Unix socket orchestrator
│   ├── Domain/                # Business logic
│   │   ├── Datasource/        # Data access interfaces
│   │   ├── Entity/            # Domain entities
│   │   ├── Repository/        # Repository interfaces
│   │   └── UseCase/           # Application use cases
│   ├── Infrastructure/        # Implementation details
│   │   ├── Datasource/        # Data source implementations
│   │   └── Repository/        # Repository implementations
│   └── Socket/                # Socket communication
│       ├── Request/           # Request handling
│       ├── Config.php         # Socket configuration
│       └── Security.php       # Authentication and security
└── unix-app/                  # Unix socket microservice
    ├── Controllers/           # Service controllers
    ├── config/                # Service configuration
    └── public/                # Service entry point

```

🧩 Core Components
-----------------

[](#-core-components)

### Unix Orchestrator (`src/Application/Unix.php`)

[](#unix-orchestrator-srcapplicationunixphp)

The orchestrator manages the lifecycle of all services:

- **Service Registration**: Adds new services to the orchestration pool
- **Process Forking**: Creates isolated processes for each service
- **Signal Handling**: Manages graceful shutdown and reload
- **Resource Monitoring**: Tracks service status and performance

Key methods:

- `registerSocket()`: Registers a new service with process isolation
- `run()`: Main orchestration loop
- `shutdown()`: Graceful service termination
- `handleSignal()`: Process OS signals (SIGTERM, SIGINT, SIGHUP)

### Socket Communication (`src/Socket/Request/`)

[](#socket-communication-srcsocketrequest)

Handles all socket-based communication with two main implementations:

1. **SocketRequest**: Unix socket communication for service-to-service interaction

    - Creates and manages Unix domain sockets
    - Handles client connections asynchronously
    - Processes incoming JSON messages
    - Provides resource cleanup and error handling
2. **HttpRequest**: HTTP-based interface for external clients

    - Accepts HTTP requests and translates to internal format
    - Routes requests to appropriate handler
    - Returns HTTP responses

### Router (`src/Application/Router.php`)

[](#router-srcapplicationrouterphp)

FastRoute-based request router:

- Maps URI paths to controller actions
- Supports middleware-like validation
- Handles authentication requirements
- Manages error responses

### Domain Layer (`src/Domain/`)

[](#domain-layer-srcdomain)

Clean, testable business logic:

- **Use Cases**: Single-responsibility actions
- **Repositories**: Data access abstractions
- **Entities**: Core business objects
- **Interfaces**: Dependency inversion

### Security (`src/Socket/Security.php`)

[](#security-srcsocketsecurityphp)

Token-based authentication system:

- Generates and validates authentication tokens
- Secures inter-service communication
- Single shared secret across services

📱 Application Demos
-------------------

[](#-application-demos)

### Unix Socket App (`unix-app/`)

[](#unix-socket-app-unix-app)

A microservices implementation that communicates via Unix sockets:

 ```
sequenceDiagram
    participant C as Client
    participant S as SocketRequest
    participant R as Router
    participant Ctrl as Controller

    C->>S: Connect to socket
    C->>S: Send JSON message
    S->>S: Authentication check
    S->>R: Route request
    R->>Ctrl: Execute controller action
    Ctrl-->>R: Return response
    R-->>S: Format response
    S-->>C: Send JSON response
```

      Loading How to run:

```
php unix-app/public/index.php
```

Key files:

- `unix-app/public/index.php`: Entry point
- `unix-app/config/container.php`: DI configuration
- `unix-app/config/routers.php`: Route definitions
- `unix-app/Controllers/`: Request handlers

### REST API App (`rest-app/`)

[](#rest-api-app-rest-app)

A RESTful HTTP API implementation that shares the same core architecture:

 ```
sequenceDiagram
    participant C as HTTP Client
    participant H as HttpRequest
    participant R as Router
    participant Ctrl as Controller

    C->>H: HTTP Request
    H->>R: Route request
    R->>Ctrl: Execute controller action
    Ctrl-->>R: Return response
    R-->>H: Format response
    H-->>C: HTTP Response
```

      Loading How to run:

```
php rest-app/public/index.php
```

Key files:

- `rest-app/public/index.php`: Entry point
- `rest-app/config/container.php`: DI configuration
- `rest-app/config/routers.php`: Route definitions
- `rest-app/Controllers/`: Request handlers

🔄 Communication Flow
--------------------

[](#-communication-flow)

The full request lifecycle:

 ```
sequenceDiagram
    participant CL as Client
    participant SR as SocketRequest
    participant SC as Security
    participant RT as Router
    participant UC as UseCase
    participant RP as Repository
    participant DS as Datasource
    participant CT as Controller

    CL->>+SR: Connect to socket
    CL->>SR: Send request {path, method, data}
    SR->>SC: authenticateMessage()

    alt Authentication Failed
        SC-->>SR: false
        SR-->>CL: 401 Unauthorized
    else Authentication Successful
        SC-->>SR: true
        SR->>+UC: execute(message)
        UC->>+RP: handlerMessage(message)
        RP->>+DS: handleMessage(message)
        DS->>+RT: dispatch(method, uri, data)
        RT->>+CT: call action(params)
        CT-->>-RT: response
        RT-->>-DS: formatted response
        DS-->>-RP: response
        RP-->>-UC: response
        UC-->>-SR: response
        SR-->>-CL: JSON response
    end
```

      Loading 🔒 Security
----------

[](#-security)

Security is implemented through several layers:

1. **Token Authentication**: Shared secret between services
2. **Socket Permissions**: Filesystem-level access control
3. **Process Isolation**: Services run in separate processes
4. **Timeout Protection**: Guards against hanging connections
5. **Error Handling**: Prevents information leakage

The security token is generated at first startup and stored in `.auth_token`. This token must be included in all inter-service communications.

⚡ Performance Considerations
----------------------------

[](#-performance-considerations)

The Unix socket architecture provides significant performance advantages:

Communication MethodAverage LatencyThroughputResource UsageUnix Sockets~0.1ms~100,000 req/sVery LowHTTP REST~1-10ms~10,000 req/sLowHTTP with DB~10-100ms~1,000 req/sMediumPerformance optimizations:

- Non-blocking socket I/O
- Process-based concurrency
- Message buffering
- Resource pooling
- Micro sleep intervals

🛠️ Installation &amp; Setup
---------------------------

[](#️-installation--setup)

### Requirements

[](#requirements)

- PHP 8.4+
- Required PHP extensions:
    - `sockets`
    - `pcntl`
    - `posix`
- Composer

### Installation Steps

[](#installation-steps)

1. Clone the repository:

    ```
    git clone https://github.com/yourname/unix-socket-microservices.git
    ```
2. Install dependencies:

    ```
    composer install
    ```
3. Configure socket directory permissions:

    ```
    mkdir -p /tmp/service
    chmod 0770 /tmp/service
    ```
4. Run the application:

    ```
    # For Unix socket app
    php unix-app/public/index.php

    # For REST API
    php rest-app/public/index.php
    ```

### Docker Installation

[](#docker-installation)

```
docker build -t unix-socket-microservices .
docker run -p 8080:80 -v /tmp/service:/tmp/service unix-socket-microservices
```

📝 Usage Examples
----------------

[](#-usage-examples)

### Simple Client

[](#simple-client)

```
