GithubHelp home page GithubHelp logo

pachico / slim-swoole Goto Github PK

View Code? Open in Web Editor NEW
95.0 11.0 12.0 43 KB

Convenient library to run SlimPHP applications with Swoole

Home Page: https://github.com/pachico/slim-swoole/

License: MIT License

PHP 100.00%
slim slim-framework swoole swoole-framework

slim-swoole's Introduction

slim-swoole

Scrutinizer Code Quality Code Coverage Build Status Software License

This is a brige library to run Slim framework Slim framework applications using Swoole engine.

Overview

The main purpose of this library is to easily run your already existing SlimPHP applications using Swoole Framework. It requires you to bootstrap your application only once when you start Swoole HTTP server and, thanks to its event driven design, it will process each request reusing your already started application for better performance.

The execution sequence is as follows:

  1. You bootstrap your SlimPHP application as you would normally do.
  2. You instantiate the BrigeManager passing to it your SlimPHP application.
  3. You start Swoole's HTTP server.
  4. You bind to the on('request') event handler the BridgeManager instance which will:
    1. Transform the Swoole request to a SlimPHP based on server and request attributes.
    2. Process your request through SlimPHP's application stack (including middlewares)
    3. Merge SlimPHP Response to Swoole Response
    4. End the request. All this is done under the hood, so you will just need to call:
$bridgeManager->process($swooleRequest, $swooleResponse)->end();

(See usage paragraph for a complete example.)

Caution: it is still in development so any contribution and test will be more than welcome.

Requirements

  • PHP-CLI >= 7.0 (Required by Swoole)
  • Swoole framework (this has been tested with version 1.10.1)

Install

Via Composer

$ composer require pachico/slim-swoole

Usage

<?php

use Pachico\SlimSwoole\BridgeManager;
use Slim\Http;

require __DIR__ . '/../vendor/autoload.php';

/**
 * This is how you would normally bootstrap your Slim application
 * For the sake of demonstration, we also add a simple middleware
 * to check that the entire app stack is being setup and executed
 * properly.
 */
$app = new \Slim\App();
$app->any('/foo[/{myArg}]', function (Http\Request $request, Http\Response $response, array $args) {
    $data = [
        'args' => $args,
        'body' => (string) $request->getBody(),
        'parsedBody' => $request->getParsedBody(),
        'params' => $request->getParams(),
        'headers' => $request->getHeaders(),
        'uploadedFiles' => $request->getUploadedFiles()
    ];

    return $response->withJson($data);
})->add(function (Http\Request $request, Http\Response $response, callable $next) {

    $response->getBody()->write('BEFORE' . PHP_EOL);
    $response = $next($request, $response);
    $response->getBody()->write(PHP_EOL . 'AFTER');

    return $response;
});

/**
 * We instanciate the BridgeManager (this library)
 */
$bridgeManager = new BridgeManager($app);

/**
 * We start the Swoole server
 */
$http = new swoole_http_server("0.0.0.0", 8081);

/**
 * We register the on "start" event
 */
$http->on("start", function (\swoole_http_server $server) {
    echo sprintf('Swoole http server is started at http://%s:%s', $server->host, $server->port), PHP_EOL;
});

/**
 * We register the on "request event, which will use the BridgeManager to transform request, process it
 * as a Slim request and merge back the response
 *
 */
$http->on(
    "request",
    function (swoole_http_request $swooleRequest, swoole_http_response $swooleResponse) use ($bridgeManager) {
        $bridgeManager->process($swooleRequest, $swooleResponse)->end();
    }
);

$http->start();

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

slim-swoole's People

Contributors

imefisto avatar nick-zh avatar pachico avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slim-swoole's Issues

Swoole doesn't build in PHP versions < 7.0

Detailed description

Travis doesn't seem to be able to build in PHP 5.*. Not sure it's Travis or Swoole has dropped support for it and PEAR repository doesn't include a valid version of it anymore.

URI has no host

Detailed description

Due to the RequestTranformer::toSlim implementation, the URI gets a null host key.

Context

I wanna get the hostname in my application.

Possible implementation

Just use the \Slim\Http\Uri class to create the URI from a string.

Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

  • Version used (e.g. PHP 7.0, 7.1): 7.2
  • Operating system and version (e.g. Ubuntu 16.04, Windows 7): Alpine Docker env

Slim WithJson Response not Showing in Swoole Response

Response from Slim Controller does not parse if sent using Slim withJson method

Detailed description

I need my response to be in JSON format and the conventional way I use in the API is send the response using Slim withJson method, I tried it with Swoole and the response is blank

Cookies should be set using "cookie" method instead of "header"

Detailed description

Currently, if you set more than one cookie, the Set-Cookie header is sent once, with all the cookies comma separated, instead of sending one Set-Cookie for each cookie (like php function setcookie does).

Also there is what RFC 6265 says about it:

Origin servers SHOULD NOT fold multiple Set-Cookie header fields into
a single header field. The usual mechanism for folding HTTP headers
fields (i.e., as defined in [RFC2616]) might change the semantics of
the Set-Cookie header field because the %x2C (",") character is used
by Set-Cookie in a way that conflicts with such folding.

Context

If you need to set more than one cookie (my particular case is for using with cloudfront (aws)), the library will fold all the cookies in one single Set-Cookie header:

HTTP/1.1 200 OK
Set-Cookie: TestCookie1=Value1; TestCookie2=Value2; TestCookie3=Value3

While the right way would be:

HTTP/1.1 200 OK
Set-Cookie: TestCookie1=Value1
Set-Cookie: TestCookie2=Value2
Set-Cookie: TestCookie3=Value3

Possible implementation

I'm doing a PR request to handle this. The issue will be solved if the cookies are set using the "cookie" method from swoole server, instead of "header" method.

process function of the BridgeManager Class

public function process(\swoole_http_request $swooleRequest, \swoole_http_response $swooleResponse) {
    $slimRequest = $this->requestTransformer->toSlim($swooleRequest);
    $slimResponse = $this->app->process($slimRequest, new Http\Response());
    $swooleResponse = $this->responseMerger->mergeToSwoole($slimResponse, $swooleResponse);
    return $swooleResponse;
}

In my opinion, you should call the run of the Slim because it does some work related to the config like adding Content-Length, Content-Type Header. The dependency manager of slim is pimple, so you can change environment to a Factory Services(so does request). my way:

private $data;

public function __construct(
        App $app,
        Bridge\RequestTransformerInterface $requestTransformer = null,
        Bridge\ResponseMergerInterface $responseMerger = null
    ) 
{
        $this->app = $app;
        $container = $app->getContainer();
        $container['environment'] = $container->factory(function () {
                 return new Environment($this->data);
        });
        $container['request'] = $container->factory(function ($c) {
             return Request::createFromEnvironment($c->get('environment'));
        });
        $this->requestTransformer = $requestTransformer ?: new Bridge\RequestTransformer();
        $this->responseMerger = $responseMerger ?: new Bridge\ResponseMerger($this->app);
}

 public function process(\swoole_http_request $swooleRequest, \swoole_http_response $swooleResponse)
{
        $this->data = $this->requestTransformer->toServerData($swooleRequest);
        $slimResponse = $this->app->run(true);
        $swooleResponse = $this->responseMerger->mergeToSwoole($slimResponse, $swooleResponse);
        return $swooleResponse;
}

^_^

PHP 8 Compatible?

Hey there,
When I tried to install the package, I got the following error message:

  [InvalidArgumentException]                                                           
  Package pachico/slim-swoole has a PHP requirement incompatible with your PHP versio  
  n, PHP extensions and Composer version:                                              
    - pachico/slim-swoole requires php ^7.0 which does not match your installed versi  
  on 8.0.7.                                                                            
    - pachico/slim-swoole requires dflydev/fig-cookies ^1.0 but it is not present.     
    - pachico/slim-swoole requires psr/http-message ^1.0 but it is not present.

Selection_236

I see that the composer.json file has the following configuration:

    "require": {
        "php": "^7.0",
        "dflydev/fig-cookies": "^1.0",
        "psr/http-message": "^1.0"
    },

Is this as easy as changing it to:

    "require": {
        "php": "^7.0|^8.0",
        "dflydev/fig-cookies": "^1.0",
        "psr/http-message": "^1.0"
    },

... or would this cause other issues?

In the meantime, I added the following to my composer.json in order to install the package successfully, and I will have to make sure the environment is PHP 7.4 when I run it in Docker.

    "config": {
        "platform" : {
            "php": "7.4.0"
        }
    }

should add try... catch... statement

 $slimResponse = $this->app->process($slimRequest, new Http\Response());

Slim

 try {
    ob_start();
    $response = $this->process($this->container->get('request'), $response);
} catch (InvalidMethodException $e) {
    $response = $this->processInvalidMethod($e->getRequest(), $response);
} finally {
    $output = ob_get_clean();
}

According to the source code of Slim, here may throw a exception(InvalidMethodException)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.