Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BC Callback: request, response, ...args #25

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ It's recommended that you use Composer to install Mark.
# Usage
start.php
```php

<?php
use Mark\App;

Expand All @@ -17,16 +18,16 @@ $api = new App('http://0.0.0.0:3000');

$api->count = 4; // process count

$api->any('/', function ($requst) {
return 'Hello world';
$api->any('/', function ($request, $response) {
return $response->withBody('Hello world');
});

$api->get('/hello/{name}', function ($requst, $name) {
return "Hello $name";
$api->get('/hello/{name}', function ($request, $response, $name) {
return $response->withBody("Hello $name");
});

$api->post('/user/create', function ($requst) {
return json_encode(['code'=>0 ,'message' => 'ok']);
$api->post('/user/create', function ($request, $response) {
return $response->withBody(json_encode(['code' => 0, 'message' => 'ok']));
});

$api->start();
Expand Down
13 changes: 7 additions & 6 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,13 +156,14 @@ public function start()
public function onMessage($connection, $request)
{
static $callbacks = [];
$response = new Response();
try {
$path = $request->path();
$method = $request->method();
$key = $method . $path;
$callback = $callbacks[$key] ?? null;
if ($callback) {
$connection->send($callback($request));
$connection->send($callback($request, $response));
return null;
}

Expand All @@ -171,18 +172,18 @@ public function onMessage($connection, $request)
$callback = $ret[1];
if (!empty($ret[2])) {
$args = array_values($ret[2]);
$callback = function ($request) use ($args, $callback) {
return $callback($request, ... $args);
$callback = function ($request, $response) use ($args, $callback) {
return $callback($request, $response, ... $args);
};
}
$callbacks[$key] = $callback;
$connection->send($callback($request));
$connection->send($callback($request, $response));
return true;
} else {
$connection->send(new Response(404, [], '<h1>404 Not Found</h1>'));
$connection->send($response->withStatus(404)->withBody('<h1>404 Not Found</h1>'));
}
} catch (\Throwable $e) {
$connection->send(new Response(500, [], (string)$e));
$connection->send($response->withStatus(500)->withBody((string)$e));
}
}
}