PHP Classes

How to Use a PHP Websockets Server to Run a Laravel REST API Using the Package PHP REST API: Implement a REST API using WebSockets

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-07-11 (2 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
php-restapi 1.0The PHP License5PHP 5, Libraries, Web services, Appli...
Description 

Author

This package implements a REST API using Web sockets.

It provides an example of REST API implementation that uses the Ratchet application class to listen to WebSockets requests on a given host name and port and processes messages to handle the Web Sockets connections.

The application is implemented using regular Laravel model, view and controller classes.

Picture of Okanlawon Anuoluwapo
  Performance   Level  
Name: Okanlawon Anuoluwapo <contact>
Classes: 8 packages by
Country: Nigeria Nigeria
Innovation award
Innovation award
Nominee: 5x

Instructions

Example

<?php
namespace App;

use
Ratchet\MessageComponentInterface;
use
Ratchet\ConnectionInterface;

class
WebSocketServer implements MessageComponentInterface
{
    protected
$clients;

    public function
__construct()
    {
       
$this->clients = new \SplObjectStorage;
    }

    public function
onOpen(ConnectionInterface $conn) : void
   
{
       
$this->clients->attach($conn);
        print
"New connection started on socket server ({$conn->resourceId})\n";
    }

    public function
onMessage(ConnectionInterface $from, $msg) : void
   
{
       
$count = count($this->clients) - 1;
       
sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
           
, $from->resourceId, $msg, $count, $count == 1 ? '' : 's');

        print
"Received Message: {$msg}\n";

        foreach (
$this->clients as $client) :
           
$client->send($msg);
        endforeach;
    }

    public function
onClose(ConnectionInterface $conn) : void
   
{
       
$this->clients->detach($conn);
        print
"Connection ({$conn->resourceId}) closed\n";
    }

    public function
onError(ConnectionInterface $conn, \Exception $e) : void
   
{
        print
"Error: ({$e->getMessage()})\n";
       
$conn->close();
    }

}


// Using on server
use Ratchet\App;

$app = new App('localhost', 8000, '0.0.0.0');
$app->route('/ws', new WebSocketServer, ['*']);
$app->run();


Details

phptestapi

Project File Structure

    /phptestapi
    ??? /app
    ?   ??? /Controllers            # Controllers to handle requests
    ?   ?   ??? UserController.php
    ?   ?   ??? FileController.php
    ?   ??? /Models                 # Database models
    ?   ?   ??? User.php
    ?   ?   ??? File.php
    ?   ??? /Helpers                # Reusable helper classes
    ?   ?   ??? Response.php        # JSON response handler
    ?   ?   ??? Auth.php            # Authentication helper (e.g., token generation, validation)
    ?   ??? /Middlewares            # Middleware classes
    ?   ?   ??? AuthMiddleware.php   # Token authorization middleware
    ?   ?   ??? ValidationMiddleware.php # Input validation and sanitization
    ?   ??? /Schemas                # Schema and migration handlers
    ?   ?   ??? Schema.php          # Schema builder for migrations
    ?   ?   ??? MigrationInterface.php # Interface for migration classes
    ?   ??? /Services               # Services for business logic
    ?       ??? UserService.php
    ?       ??? FileService.php
    ??? /bootstrap
    ?   ??? bootstrap.php           # Bootstrap file for initialization and autoloading
    ??? /config
    ?   ??? database.php            # Database configuration file
    ??? /cli
    ?   ??? run_migrations.php      # Command-line script to run migrations
    ?   ??? seed_database.php       # Command-line script to seed database (optional)
    ??? /migrations                 # Migration files
    ?   ??? 2024_11_05_134629_create_users_table.php
    ?   ??? 2024_11_05_135537_create_files_table.php
    ??? /public                     # Publicly accessible files
    ?   ??? index.php               # Entry point for the application
    ??? /routes
    ?   ??? api.php                 # Route definitions for API endpoints
    ??? /storage                    # Storage for logs, uploaded files, etc.
    ?   ??? /logs
    ?       ??? app.log             # Application log file
    ??? /tests                      # Test files
    ?   ??? ExampleTest.php
    ??? composer.json               # Composer dependencies
    ??? helpers.php                 # Global helper functions

Folder and File Descriptions

  • /app: Contains the core application logic.

    - Controllers: Manage incoming requests and call services or models as needed. - Models: Represent database tables and encapsulate database interactions. - Helpers: Include reusable utilities like Response for JSON handling and Auth for authentication. - Middlewares: Define middleware classes for authorization, validation, etc. - Schemas: Store classes related to schema migrations, including Schema for creating and dropping tables and interfaces for migrations. - Services: Handle the business logic for each resource, providing a layer between controllers and models.

  • /bootstrap: Contains the bootstrap.php file, where the project initializes configurations, autoloading, and dependencies.
  • /config: Holds configuration files like database.php, where database connection settings are defined.
  • /cli: Contains command-line scripts for running migrations, seeding data, and any other CLI-related tasks.
  • /migrations: Holds individual migration files. Each migration file contains an up and down method for schema changes.
  • /public: Contains index.php, the main entry point for HTTP requests. This file is publicly accessible and routes requests to the appropriate controller.
  • /routes: Defines API routes, typically grouped in api.php for organizing route definitions.
  • /storage: Houses files for logging and other temporary data. Inside, logs stores log files.
  • /tests: Contains test files for application testing.
  • composer.json: Manages project dependencies with Composer.
  • helpers.php: A global file for any helper functions (e.g., the response() function for Response).

This structure provides clear separation of concerns, making the project maintainable, scalable, and easy to navigate as it grows.

Run Project

$ php -S localhost:8000 -t public


  Files folder image Files (45)  
File Role Description
Files folder imageapp (8 directories)
Files folder imagebootstrap (1 file)
Files folder imagecli (4 files)
Files folder imageconfig (4 files)
Files folder imagemigrations (2 files)
Files folder imagepublic (2 files)
Files folder imageroutes (1 file)
Files folder imagestorage (1 directory)
Files folder imagetests (1 file)
Accessible without login Plain text file .env.example Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file composer.lock Data Auxiliary data
Plain text file helpers.php Class Class source
Accessible without login Plain text file README.md Doc. Documentation
Accessible without login Plain text file server.php Example API example script

  Files folder image Files (45)  /  app  
File Role Description
Files folder imageExceptions (1 file)
Files folder imageGateways (2 files)
Files folder imageHelpers (1 file)
Files folder imageHttp (3 files, 2 directories)
Files folder imageInterfaces (2 files)
Files folder imageModels (2 files)
Files folder imageSchemas (2 files)
Files folder imageServices (1 file)

  Files folder image Files (45)  /  app  /  Exceptions  
File Role Description
  Plain text file ValidationException.php Class Class source

  Files folder image Files (45)  /  app  /  Gateways  
File Role Description
  Plain text file PayPalGateway.php Class Class source
  Plain text file StripeGateway.php Class Class source

  Files folder image Files (45)  /  app  /  Helpers  
File Role Description
  Plain text file Response.php Class Class source

  Files folder image Files (45)  /  app  /  Http  
File Role Description
Files folder imageControllers (6 files)
Files folder imageMiddleware (3 files)
  Plain text file Request.php Class Class source
  Plain text file Route.php Class Class source
  Plain text file Router.php Class Class source

  Files folder image Files (45)  /  app  /  Http  /  Controllers  
File Role Description
  Plain text file AuthController.php Class Class source
  Plain text file Controller.php Class Class source
  Plain text file EmailController.php Class Class source
  Plain text file FileController.php Class Class source
  Plain text file PaymentController.php Class Class source
  Plain text file UserController.php Class Class source

  Files folder image Files (45)  /  app  /  Http  /  Middleware  
File Role Description
  Plain text file AuthMiddleware.php Class Class source
  Plain text file RateLimitMiddleware.php Class Class source
  Plain text file Validator.php Class Class source

  Files folder image Files (45)  /  app  /  Interfaces  
File Role Description
  Plain text file ModelInterface.php Class Class source
  Plain text file PaymentGatewayInterface.php Class Class source

  Files folder image Files (45)  /  app  /  Models  
File Role Description
  Plain text file BaseModel.php Class Class source
  Plain text file User.php Class Class source

  Files folder image Files (45)  /  app  /  Schemas  
File Role Description
  Plain text file MigrationInterface.php Class Class source
  Plain text file Schema.php Class Class source

  Files folder image Files (45)  /  app  /  Services  
File Role Description
  Plain text file PaymentService.php Class Class source

  Files folder image Files (45)  /  bootstrap  
File Role Description
  Accessible without login Plain text file app.php Example Example script

  Files folder image Files (45)  /  cli  
File Role Description
  Accessible without login Plain text file generate_jwt_secret.php Aux. Configuration script
  Accessible without login Plain text file make_migration.php Aux. Configuration script
  Accessible without login Plain text file run_migrations.php Example Example script
  Accessible without login Plain text file seed_database.php Example Example script

  Files folder image Files (45)  /  config  
File Role Description
  Plain text file Database.php Class Class source
  Plain text file JWT.php Class Class source
  Plain text file RateLimiter.php Class Class source
  Plain text file Session.php Class Class source

  Files folder image Files (45)  /  migrations  
File Role Description
  Plain text file 2024_11_11_211239_create_users_table.php Class Class source
  Plain text file 2024_11_11_211244_create_files_table.php Class Class source

  Files folder image Files (45)  /  public  
File Role Description
  Accessible without login Plain text file .htaccess Data Auxiliary data
  Accessible without login Plain text file index.php Aux. Configuration script

  Files folder image Files (45)  /  routes  
File Role Description
  Plain text file api.php Class Class source

  Files folder image Files (45)  /  storage  
File Role Description
Files folder imagelogs (1 file)

  Files folder image Files (45)  /  storage  /  logs  
File Role Description
  Accessible without login Plain text file error.log Data Auxiliary data

  Files folder image Files (45)  /  tests  
File Role Description
  Plain text file ExampleTest.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0