Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

License

NotificationsYou must be signed in to change notification settings

reactive-apps/command-http-server

Repository files navigation

Build StatusLatest Stable VersionTotal DownloadsCode CoverageLicensePHP 7 ready

Install

To install viaComposer, use the command below, it will automatically detect the latest version and bind it with^.

composer require reactive-apps/command-http-server

Controllers

Controllers come in two different flavours static and instantiated controllers.

Static Controllers

Static controllers are recommended when your controller doesn't have any dependencies like this ping controller used forupdown.io health checks.Note:/ping isn't a updown standard but it's my personalstandard of doing health checks for my apps This controller only has a single method with a single route and nodependencies:

<?phpdeclare(strict_types=1);namespaceApp\Controller;usePsr\Http\Message\ResponseInterface;usePsr\Http\Message\ServerRequestInterface;useReactiveApps\Command\HttpServer\Annotations\Method;useReactiveApps\Command\HttpServer\Annotations\Routes;useRingCentral\Psr7\Response;finalclass Ping{/**     * @Method("GET")     * @Routes("/ping")     *     * @param  ServerRequestInterface $request     * @return ResponseInterface     */publicstaticfunctionping(ServerRequestInterface$request):ResponseInterface    {returnnewResponse(200,            ['Content-Type' =>'text/plain'],'pong'        );    }}

Instantiated Controllers

Instantiated Controllers on the other hand will be instantiated and kept around to handle more requests in the futureas such they can have dependencies injected. The example below is a controller that has the event loop injected to waitfor a random number of seconds before returning the response. It also uses coroutines to make the code more readable:

<?phpdeclare(strict_types=1);namespaceApp\Controller;usePsr\Http\Message\ResponseInterface;usePsr\Http\Message\ServerRequestInterface;useReact\EventLoop\LoopInterface;useReactiveApps\Command\HttpServer\Annotations\Method;useReactiveApps\Command\HttpServer\Annotations\Routes;useReactiveApps\Command\HttpServer\Annotations\Template;useReactiveApps\Command\HttpServer\TemplateResponse;useWyriHaximus\Annotations\Coroutine;usefunctionWyriHaximus\React\timedPromise;/** * @Coroutine()) */finalclass Root{/** @var LoopInterface */private$loop;/** @var int */private$time;publicfunction__construct(LoopInterface$loop)    {$this->loop =$loop;$this->time =\time();    }/**     * @Method("GET")     * @Routes("/")     * @Template("root")     *     * @param  ServerRequestInterface $request     * @return ResponseInterface     */publicfunctionroot(ServerRequestInterface$request)    {$start =\time();yieldtimedPromise($this->loop,\random_int(1,5));return (newTemplateResponse(200,            ['Content-Type' =>'text/plain']        ))->withTemplateData(['uptime' => (\time() -$this->time),'took' => (\time() -$start),        ]);    }}

Routing

Routing is done through annotations on the method handling the routes. Each method can handle multiple routes but it'srecommended to only map routes that fit the the method.

For example the following annotation will map the current method to/ (note: all routes are required to beprefixed with/):@Routes("/")

A multi route annotation has a slightly different syntax, in the following both/old and/new will be handled bythe same method:

@Routes({"/old","/new"})

The underlying engine for routes isnikic/fast-route which also makes complexroutes like this one possible:

@Route("/{map:(?:wow_cata_draenor|wow_cata_land|wow_cata_underwater|wow_legion_azeroth|wow_battle_for_azeroth|wow_cata_elemental_plane|wow_cata_twisting_nether|wow_comp_wotlk)}/{zoom:1|2|3|4|5|6|7|8|9|10}/{width:[0-9]{1,5}}/{height:[0-9]{1,5}}/{center:[a-zA-Z0-9\`\-\~\_\@\%]{1,35}}{blips:/blip\_center|/[a-zA-Z0-9\`\-\~\_\@\%\[\]]{3,}.+|}.{quality:png|hq.jpg|lq.jpg}")

The different route components likemap, andcenter are available from the request object with:

$request->getAttribute('center');

Templates

A route can render a template upon completion it needs an annotation and return/resolve with aTemplateResponseholding the data required for that template. For example:

/** * @Template("root") */publicfunctionroot(ServerRequestInterface$request){return (newTemplateResponse(200,        ['Content-Type' =>'text/plain']    ))->withTemplateData(['beer' =>'Allmouth',// https://untappd.com/user/WyriHaximus/checkin/745226210    ]);}

Blocking operations in requests

While we aim for building a completely non-blocking application we can't escape the truth that there might always beparts of our application that would block the loop. For those situations there are two ways provided to deal with thosesituations:

  • Child Process (slow, spawns full PHP processes to handle the request)
  • Threads (fast, uses threads to do the work, requires ZTS version of PHP)

Child Processes

Works on most if not all systems but requires a full PHP processes per worker. Start up can be slow and communicationwith the child process goes over a socket. Add the@ChildProcess annotation to handle that specific action in achild process.

Threads

Works only on ZTS PHP builds, but in return starts up almost instantly, communication is directly in memory thus neverleaving the application server. Add the@Thread annotation to handle that specific action in a thread.

Annotations

  • @ChildProcess - Runs controller actions inside a child process
  • @Coroutine - Runs controller actions inside a coroutine
  • @Method - Allowed HTTP methods (GET, POST, PATCH, etc)
  • @Routes - Routes to use the given method for
  • @Template - Template to use when a TemplateResponse is used
  • @Thread - Runs controller actions inside a thread (preferred over use child processes)

Options

  • http-server.address - The IP + Port to listen on, for example:0.0.0.0:8080
  • http-server.hsts - Whether or not to set HSTS headers
  • http-server.public - Public webroot to serve, note only put files in here everyone is allowed to see
  • http-server.public.preload.cache - Custom cache to store the preloaded webroot files, stored in memory by default
  • http-server.middleware.prefix - An array with react/http middleware added before the accesslog and webroot serving middleware
  • http-server.middleware.suffix - An array with react/http middleware added after the accesslog and webroot serving middleware and before the route middleware and request handler
  • http-server.pool.ttl - TTL for a child process to wait for it's next task
  • http-server.pool.min - Minimum number of child processes
  • http-server.pool.max - maximum number of child processes
  • http-server.rewrites - Rewrites request path internally from one path to the other, invisible for visitors

License

The MIT License (MIT)

Copyright (c) 2019 Cees-Jan Kiewiet

Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors3

  •  
  •  
  •  

Languages


[8]ページ先頭

©2009-2025 Movatter.jp