Usage Guide
Comprehensive guide to the WPZylos HTTP package.
Table of Contents
- 1. Capturing the Request
- 2. Reading Input
- 3. Sanitized Input Helpers
- 4. Request Inspection
- 5. Creating Responses
- 6. Response Instance Methods
- 7. Middleware Pipeline
- 8. Service Provider Registration
1. Capturing the Request
Use Request::capture() to create a request from the current PHP superglobals. WordPress-added slashes are automatically removed via wp_unslash.
use WPZylos\Framework\Http\Request;
// Capture from $_GET, $_POST, $_FILES, $_SERVER
$request = Request::capture();
// With plugin context
$request = Request::capture($context);
You can also construct a request manually for testing:
$request = new Request(
query: ['page' => '2'],
request: ['name' => 'John'],
files: [],
server: ['REQUEST_METHOD' => 'POST'],
);
2. Reading Input
General Input
input() checks POST data first, then falls back to GET:
$name = $request->input('name');
$name = $request->input('name', 'Guest'); // with default
All Input
$all = $request->all(); // merged GET + POST
Subset of Input
// Only specified keys
$credentials = $request->only(['username', 'password']);
// Everything except specified keys
$data = $request->except(['_token', 'password_confirmation']);
Check if Key Exists
if ($request->has('email')) {
// Key exists in POST or GET
}
Source-Specific Access
// GET parameters only
$page = $request->query('page', 1);
$sort = $request->query('sort', 'created_at');
// POST parameters only
$name = $request->post('name');
$email = $request->post('email', '');
3. Sanitized Input Helpers
These methods retrieve input and apply WordPress sanitization functions automatically. Use them instead of manually sanitizing.
| Method | Return Type | WordPress Function | Description |
|---|---|---|---|
text($key, $default) | string | sanitize_text_field() | Plain text, strips tags and extras |
textarea($key, $default) | string | sanitize_textarea_field() | Multi-line text, preserves newlines |
email($key, $default) | string | sanitize_email() | Valid email characters only |
url($key, $default) | string | esc_url_raw() | Safe URL for database storage |
int($key, $default) | int | (int) cast | Integer value |
absint($key, $default) | int | absint() | Absolute (non-negative) integer |
float($key, $default) | float | (float) cast | Float value |
bool($key, $default) | bool | filter_var(FILTER_VALIDATE_BOOLEAN) | Boolean (true, 1, 'yes', 'on' → true) |
html($key, $default) | string | wp_kses_post() | Rich HTML (post-content level allowed tags) |
array($key, $default) | array | Type check | Returns array or default if not an array |
Examples
// Form processing with sanitized helpers
$title = $request->text('title');
$content = $request->html('content');
$email = $request->email('contact_email');
$website = $request->url('website');
$page = $request->absint('page', 1);
$price = $request->float('price', 0.0);
$active = $request->bool('is_active');
$bio = $request->textarea('bio');
$tags = $request->array('tags', []);
4. Request Inspection
HTTP Method
$method = $request->method(); // 'GET', 'POST', 'PUT', etc.
if ($request->isMethod('POST')) { /* ... */ }
if ($request->isPost()) { /* ... */ }
if ($request->isGet()) { /* ... */ }
AJAX Detection
Checks the X-Requested-With header and WordPress wp_doing_ajax():
if ($request->isAjax()) {
return Response::json(['status' => 'ok']);
}
URI and Path
$uri = $request->uri(); // '/admin.php?page=settings&tab=general'
$path = $request->path(); // '/admin.php'
Headers
Header names are normalized (dashes converted to underscores, uppercased):
$contentType = $request->header('Content-Type');
$auth = $request->header('Authorization', 'none');
Uploaded Files
Returns the raw $_FILES entry for a key, or null if not present:
$file = $request->file('avatar');
if ($file !== null) {
$tmpName = $file['tmp_name'];
$size = $file['size'];
}
Client IP
$ip = $request->ip(); // REMOTE_ADDR or '127.0.0.1'
Plugin Context
$context = $request->context(); // ContextInterface|null
5. Creating Responses
HTML Response
use WPZylos\Framework\Http\Response;
$response = Response::html('<h1>Hello World</h1>');
$response = Response::html($renderedView, 201);
Sets Content-Type: text/html; charset=utf-8.
JSON Response
$response = Response::json(['status' => 'ok', 'data' => $items]);
$response = Response::json(['user' => $user], 201);
Sets Content-Type: application/json; charset=utf-8. Throws \JsonException on encoding failure.
Redirect Response
$response = Response::redirect('/dashboard');
$response = Response::redirect(admin_url('admin.php?page=settings'), 301);
The URL is sanitized with esc_url_raw(). Default status is 302.
Empty Response
$response = Response::empty(); // 204 No Content
$response = Response::empty(201); // 201 Created with no body
Error Response
$response = Response::error('Something went wrong'); // 500
$response = Response::error('Not found', 404); // 404
$response = Response::error('Validation failed', 422); // 422
Returns JSON: {"error": "Something went wrong"}.
6. Response Instance Methods
Reading Response State
$content = $response->getContent();
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();
Modifying Responses (Fluent API)
All setters return $this for chaining:
$response = Response::json($data)
->setStatusCode(201)
->header('X-Custom-Header', 'value')
->header('Cache-Control', 'no-cache');
Sending Responses
// Send headers and echo content
$response->send();
// Send and terminate script (useful for AJAX handlers)
$response->sendAndExit();
send() checks headers_sent() before attempting to send HTTP headers, making it safe to call in various WordPress contexts.
7. Middleware Pipeline
Creating Middleware
Implement MiddlewareInterface for type-safe middleware:
use WPZylos\Framework\Http\Contracts\MiddlewareInterface;
use WPZylos\Framework\Http\Request;
use WPZylos\Framework\Http\Response;
class AuthMiddleware implements MiddlewareInterface
{
public function handle(Request $request, callable $next): Response
{
if (!is_user_logged_in()) {
return Response::redirect(wp_login_url());
}
return $next($request);
}
}
Or use a callable (closure):
$rateLimiter = function (Request $request, callable $next): Response {
// Check rate limit...
return $next($request);
};
Running the Pipeline
use WPZylos\Framework\Http\Pipeline;
$response = (new Pipeline($container))
->send($request)
->through([
AuthMiddleware::class, // Resolved from container
new LoggingMiddleware(), // Instance
$rateLimiter, // Callable
])
->then(function (Request $request): Response {
return Response::json(['message' => 'Hello!']);
});
Automatic Response Conversion
The then() handler return value is automatically converted:
| Return Type | Converted To |
|---|---|
Response | Used as-is |
string | Response::html($string) |
array | Response::json($array) |
null | Response::empty() |
8. Service Provider Registration
The HttpServiceProvider registers the request and pipeline with the container:
use WPZylos\Framework\Http\HttpServiceProvider;
// In your application bootstrap
$app->register(new HttpServiceProvider());
What Gets Registered
| Binding | Type | Description |
|---|---|---|
Request::class | Singleton | Captured from superglobals via Request::capture() |
'request' | Singleton (alias) | Same instance as Request::class |
Pipeline::class | Factory | New instance each call |
Resolving from Container
// Get the current request
$request = $container->get(Request::class);
$request = $container->get('request');
// Create a new pipeline
$pipeline = $container->get(Pipeline::class);