ergebnis/http-method
Tiny PHP package providing named constants for HTTP request methods (GET, POST, PUT, DELETE, etc.). Use it to avoid magic strings and share a single source of truth across frameworks, libraries, and your own code.
Installation:
composer require ergebnis/http-method
No additional configuration is required—just autoload the package.
First Use Case:
Replace hardcoded HTTP method strings (e.g., "GET", "POST") with constants for type safety and IDE autocompletion.
use Ergebnis\HttpMethod\Method;
// Instead of:
$method = "GET";
// Use:
$method = Method::GET;
Where to Look First:
Method class (e.g., Method::GET, Method::POST, Method::PATCH).Method::isValid() to check if a string is a valid HTTP method.Method::fromString() to convert strings to constants safely.Request Handling:
use Ergebnis\HttpMethod\Method;
use Symfony\Component\HttpFoundation\Request;
$request = new Request();
$method = Method::fromString($request->getMethod()); // Safe conversion
Route Definitions:
Route::get('/users', [UserController::class, 'index']); // Use constants for clarity
Route::post('/users', [UserController::class, 'store']);
API Contracts:
public function validateMethod(string $method): void
{
if (!Method::isValid($method)) {
throw new \InvalidArgumentException("Invalid HTTP method");
}
}
Middleware:
public function handle(Request $request, Closure $next)
{
if (Method::fromString($request->getMethod()) === Method::PATCH) {
// Custom logic for PATCH requests
}
return $next($request);
}
public function create(Method $method)).$this->assertEquals(Method::POST, Method::fromString("post"));
Symfony\Component\HttpFoundation\Request/Response.FormRequest validation:
public function rules()
{
return [
'method' => ['required', Rule::in(array_column(Method::cases(), 'value'))],
];
}
Case Sensitivity:
Method::fromString() converts strings to uppercase (e.g., "post" → Method::POST).strtoupper() with fromString() to prevent double-conversion.Non-Standard Methods:
X-MY-CUSTOM-METHOD).Method::isValid() to filter out non-standard methods.Deprecation:
PURGE) may not be included immediately. Check the releases for updates.Invalid Method Errors:
Method::isValid($method) to validate before processing.IDE Issues:
config/http-method.php exists. All functionality is self-contained.Custom Methods:
Method enum (PHP 8.1+) or create a wrapper class for project-specific methods:
class CustomMethod extends Method
{
public const PURGE = 'PURGE';
}
Integration with Laravel:
trait UsesHttpMethods
{
protected function isGetRequest(): bool
{
return request()->method() === Method::GET;
}
}
Localization:
"Method {method} is not allowed"). Use Method::value to get the raw string:
__('Method :method is not allowed', ['method' => Method::POST->value]);
How can I help you explore Laravel packages today?