Download the PHP package michaelyousrie/batframe without Composer
On this page you can find all versions of the php package michaelyousrie/batframe. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download michaelyousrie/batframe
More information about michaelyousrie/batframe
Files in michaelyousrie/batframe
Package batframe
Short Description A tiny Flask-like PHP microframework where each public method is an endpoint and routes are inferred from method names.
License MIT
Informations about the package batframe
Batframe
A tiny, Flask-like PHP microframework. You extend one class, write public methods, and each method becomes an HTTP endpoint whose route is inferred from its name. No route files, no decorators, no config to get started, but every moving part is swappable when you outgrow the defaults.
Batframe is for the project that is too small for Laravel or Symfony: a quick JSON API, a handful of endpoints, or a small static site.
Requirements
- PHP 8.1+
Install
The fastest way to start is the skeleton, which scaffolds a ready-to-run app
(route traits, Blade views, static pages, a front controller, and .env):
See batframe-skeleton for details. To add Batframe to an existing project instead:
The routing convention
The route is derived entirely from the method name and its parameters.
| Method | Route |
|---|---|
index() |
GET / |
getUsers() |
GET /users |
getUserProfile() |
GET /user/profile |
getUser(int $id) |
GET /user/{id} |
getUserPost(int $userId, int $postId) |
GET /user/post/{userId}/{postId} |
postUsers() |
POST /users |
putUser(int $id) |
PUT /user/{id} |
deleteUser(int $id) |
DELETE /user/{id} |
Rules:
- The method name must start with an HTTP verb:
get,post,put,patch,delete,head,options. That sets the HTTP method. - The remaining PascalCase words become
/-separated path segments, lowercased. - No auto-pluralization: the path is taken literally from the name.
getUser()is/user; for/usersname itgetUsers(). index()is special-cased toGET /.- A public method that does not start with a verb is treated as an internal helper and is
not exposed as a route. Handy for shared logic; keep truly private helpers
private.
Route parameters
- Typed scalar parameters (
int,string,float,bool) become{placeholder}path segments in declared order.int/floatalso constrain the segment, so/user/abcwill not matchgetUser(int $id). - A parameter typed
Requestis injected and may appear in any position:postUsers(Request $request).
Return values
Whatever a handler returns is turned into a response:
| Return value | Response |
|---|---|
a Response |
sent as-is |
an array / scalar / JsonSerializable |
application/json |
a string |
text/html |
null |
204 No Content |
Grouping routes into traits
Routes don't have to live directly on your app class. Any verb-prefixed public method composed in from a trait is registered exactly like an inline method, so you can group related endpoints together and keep the app class tiny:
The same convention rules apply inside a trait (verb prefix required, verbless
methods are helpers). See example/src/Routes/ for a
working split.
Requests
You don't have to inject the Request to reach it. The request() helper returns
the request being handled anywhere in your app:
Responses
Helper functions are available too: view(), json(), response(), redirect(),
abort(404), env(), config(), session(), cache(), request(), validate(),
validateMany().
Sessions
Batframe wraps PHP's native file-based sessions in a small, intuitive helper. The session starts lazily the first time you touch it, so no cookie is sent unless you actually use it, and there's nothing to configure.
session() with no argument returns the Batframe\Helpers\Session instance;
session('key') reads a value; session(['key' => 'value']) writes.
Cache
Batframe ships a small file-based cache, in the same spirit as the session helper. Every entry
carries its own time-to-live, so you decide per item whether it is short-lived or sticks around.
Pass a ttl in seconds, or null (the default) to keep it until you forget it.
cache() with no argument returns the Batframe\Helpers\Cache instance; cache('key') reads;
cache(['key' => 'value'], $ttl) writes. Entries live as files under the app's cache directory,
so they survive across requests. Constructing new Cache() with no directory gives you a
request-scoped, in-memory store instead.
Validation
Batframe validates a single value against a list of rules. Rules are built from the
Rule class, so the call site stays type-safe with no magic strings. validate()
returns true when every rule passes, or throws a ValidationException (HTTP 422)
that Batframe's error pipeline renders for you, with the messages in the JSON body.
The available rules: Rule::required(), Rule::nullable(), Rule::string(),
Rule::integer(), Rule::boolean(), Rule::numeric(), Rule::alphaNum(),
Rule::alpha(), Rule::email(), Rule::url(), Rule::min($n), Rule::max($n),
Rule::between($min, $max), Rule::in([...]), Rule::regex($pattern).
nullable lets a null value skip the remaining rules; required rejects an empty
value (null, '', or []). The size rules (min/max/between) measure a string's
length, an array's element count, or an int/float's value; a numeric string is measured
by length, so cast it first if you mean to compare the value:
validate((int) $qty, [Rule::between(1, 5)]).
validate() with no arguments returns the Batframe\Validation\Validator instance,
whose passes() / fails() methods do the same checks without throwing.
Views (Blade)
Templating is powered by BladeOne, a dependency-free engine
with the Blade syntax you know (@extends, @section, @foreach, {{ $var }}). Templates live
in the views/ directory:
The engine is swappable, implement Batframe\View\ViewEngine and pass it in via the
view_engine config key (or Response::setViewEngine(...)).
Static pages
Drop a Blade or HTML file in the pages/ directory and it is served automatically when a request
path matches its name, with no controller method needed. pages/about.blade.php answers
/about; pages/index.blade.php answers /. This makes small static sites trivial.
Configuration & environment
A .env file in your project root is loaded automatically (via vlucas/phpdotenv). Read values
with env('KEY', $default); literals like true/false/null are coerced. APP_DEBUG=true
turns on detailed error pages.
Pass overrides to the constructor:
By convention, if you don't set base_path, Batframe assumes your app class lives in
<project>/src/ and derives the project root from there.
Project layout
The front controller is a one-liner:
Running locally
A complete, runnable example lives in example/.
Testing
Error handling
Throw an HttpException (or call abort()) to abort with a status code:
Errors are rendered as JSON or HTML based on content negotiation. When APP_DEBUG=true, 500s
include the exception class, location and stack trace; in production they show a generic page.
License
MIT
All versions of batframe with dependencies
ext-json Version *
eftec/bladeone Version ^4.0
vlucas/phpdotenv Version ^5.5