corsair/m360

M360API PHP Middleware with support to Symfony, and Laravel

v0.0.8 2023-03-14 13:43 UTC

This package is auto-updated.

Last update: 2024-03-29 07:49:17 UTC


README

The M360 PHP Middleware is a dependency that gets consumed by a PHP Server built using one of these frameworks Symfony, and Laravel.

The middleware is developed using native PHP and includes interfaces that facilitate using it with the above mentioned frameworks.

Installation

Installing with Symfony

Navigate to your symfony project directory using your terminal and then execute the below commands:

$ cd path_to_my_symfony_project
$ composer require m360.mw.php

Then Open the config/bundles.php file in your editor and add the middleware bundle class to it:

<?php

return [
    ...
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    M360\frameworks\Symfony\M360MiddlewareBundle::class => ['all' => true],
    ...
];

That's it! the M360 PHP middleware has now been installed in your symfony project.

Installing with Laravel

Navigate to your laravel project directory using your terminal. Edit your composer.json file and under scripts/post-autoload-dump paste the below command:

"scripts": {
    "post-autoload-dump": [
        "@php artisan m360:install"
    ],
}

Then, execute the below command in your terminal:

$ cd path_to_my_laravel_project
$ composer require m360.mw.php

That's it! the M360 PHP middleware has now been installed in your laravel project.

Configuration

Now that the M360 Middleware is installed, navigate to your project directory and create a new contract file for your microservice. The Contract file is a simple JSON file that contains the list of API endpoints that are supported in your microservice.

Example:
{
  "name": "laravel",
  "group": "Testing",
  "version": 1,
  "ports": {
    "data": 443,
    "maintenance": 443
  },
  "apis": {
    "main": {
      "get": {
        "/": {
          "access": false, 
          "label": "List Data Entries"
        },
        "/:id": {
          "access": false,
          "label": "Get one Data Entry using its ID"
        }
      },
      "post": {
        "/": {
          "access": true,
          "label": "Create new Data Entry"
        }
      },
      "patch": {
        "/:id": {
          "access": true,
          "label": "Update fields in the Data Entry using its ID"
        }
      },
      "put": {
        "/:id": {
          "access": true,
          "label": "Override the Data Entry using its ID"
        }
      },
      "delete": {
        "/:id": {
          "access": true,
          "label": "Delete the Data entry using its ID"
        }
      }
    },
    "maintenance": {
      "get": {
        "/cache/clear": {
          "access": false,
          "label": "Clear the Cache of your Microservice"
        }
      }
    }
  }
}

You can learn more about service contracts on this page "M360API Middleware Knowledgebase".

Both symfony and laravel use an environment file to set the global configuration values that get passed to their applications.

Using the same approach, edit the .env file that is located on the root level of your project's directory and add the below variables:

Symfony
APP_IP=https://myapi.symfony.local
APP_PLATFORM=manual
M360_SERVICE_CONTRACT=/absolute_path_to_my_symfony_project/contract.json
Laravel
APP_IP=https://myapi.laravel.local
APP_PLATFORM=manual
M360_SERVICE_CONTRACT=/absolute_path_to_my_laravel_project/contract.json

Usage

Now that the middleware is installed, you can use the SDK inside your APIs and Controllers and the CLI commands it contains.

Symfony

API

Symfony uses dependency injection to inject services into the controllers of your APIs. The below examples demonstrates how to use the middleware with symfony using dependency injection.

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

# add the namespace of the middleware
use M360\frameworks\Symfony\Service\M360MiddlewareService;

class HelloController extends AbstractController
{
    # create a private property for the middleware service
	private M360MiddlewareService $M360mw;

    # declare the middleware service as a dependency
	public function __construct (M360MiddlewareService $m360MiddlewareService) {
	
	    # assing the middleware service and call the init method
		$this->M360mw = $m360MiddlewareService;
		$this->M360mw->init();
	}

	/**
	 * @Route("/hello", name="hello")
	 */
	public function hello (): Response {

		$response = (object)[];
		
		# you can now use the SDK of the middleware in your code 
		# this example pulls a copy of the registry settings using the middleware and sets it in the response
		$reg = $this->M360mw->SDK->registry->get("registry");
		if(!empty($reg)){
			$response = $reg;
		}

		return new Response(json_encode($response, JSON_PRETTY_PRINT), 200, ['Content-Type' => 'application/json']);
	}
}

Commands

In your terminal, navigate to your symfony project directory and run the bin/console command. The commands that the M360 middleware added will be available in the list:

m360
  m360:autoregister           Auto Register this laravel server in M360 Gateway
  m360:reloadregistry         Reloads the Registry of the M360 middleware in this laravel server

Laravel

API

Laravel supports middlewares and that enables bootstrapping the m360 middleware before the request reaches the business logic and your code. Therefore, using the m360 middleware is straight forward with laravel.

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function test(Request $request){
        $response = (object)[];
        
        # the middleware is already attached to the Request Object and you don't need to declare anything
        # use the SDK of the middleware in your code
        # this example pulls a copy of the registry settings using the middleware and sets it in the response
        $reg = $request->M360->registry->get("registry");
        if(!empty($reg)){
            $response = $reg;
        }
        return response(json_encode($response, JSON_PRETTY_PRINT), 200)->header('Content-Type', 'text/plain');
    }
}

Commands

In your terminal, navigate to your laravel project directory and run the php artisan command. The commands that the M360 middleware added will be available in the list:

m360
  m360:autoregister     Auto Register this laravel server in M360 Gateway
  m360:install          Install the M360 Middleware
  m360:reloadregistry   Reloads the Registry of the M360 middleware in this laravel server

The m360:install command was already triggered when you ran composer require m360.mw.php. You do not need to run this command again. However, the command is present should require to reset your installation.

Commands Explained

CommandDescription
m360:autoregisterThis command should run everytime you modify the contract of your microservice and add/modify/remove API endpoints. It sends an updated copy of the contract to the gateway so the later can stay aware of what endpoints your microservice is currently supporting.
m360:reloadregistryThis command refreshes the local cached registry settings copy that got fetched from the gateway. Run this command every time the settings of the current environment change to get the latest updated version.

Containerized Deployment

When you're about to deploy your PHP microservice on a containerized cluster, the behavior changes a bit. Modify the .env file and include the extra below variables depending on which technology you will use.

Deploying on Docker

When deploying on Docker, please provide the extra options below. Without these options, the handshake between the middleware and the gateway will fail, along with any maintenance operation that gets triggered from the console onto this microservice.

OptionData TypeMandatoryDescription
platformStringYESvalue equals 'docker'
networkStringYESvalue equals the docker network attached to this docker service
serviceStringYESvalue equals the name of the docker service
containerIPStringNOvalue is the internal IP address of the docker container in the docker service

Example

APP_PLATFORM=docker
APP_PLATFORM_OPTIONS_SERVICE=my_docker_service_name
APP_PLATFORM_OPTIONS_NETWORK=my_docker_network_name

Deploying on Kubernetes

When deploying on Kubernetes, please provide the extra options below. Without these options, the handshake between the middleware and the gateway will fail, along with any maintenance operation that gets triggered from the console onto this microservice.

OptionData TypeMandatoryDescription
platformStringYESvalue equals 'kubernetes'
namespaceStringYESvalue equals the kubernetes namespace where your deployment will run
serviceStringYESvalue equals the name of the kubernetes service that is attached to the your deployment
exposedPortStringYESvalue equals the exposed port kubernetes service
APP_PLATFORM=kubernetes
APP_PLATFORM_OPTIONS_NAMESPACE=my_kubernetes_namespace_value
APP_PLATFORM_OPTIONS_PORTS=my_kubernetes_service_exposed_port_value

The Middleware includes examples on how you can consume it with these servers.

These examples are located inside the frameworks folder in this repository.

Reference: M360 Middleware Official Documentation