Download the PHP package vlucas/bulletphp without Composer
On this page you can find all versions of the php package vlucas/bulletphp. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download vlucas/bulletphp
More information about vlucas/bulletphp
Files in vlucas/bulletphp
Package bulletphp
Short Description A heierarchical resource-oriented micro-framework built on nested closures instead of route-based callbacks
License BSD
Homepage http://bulletphp.com
Informations about the package bulletphp
Bullet
Bullet is a resource-oriented micro PHP framework built around HTTP URIs. Bullet takes a unique functional-style approach to URL routing by parsing each path part independently and one at a time using nested closures. The path part callbacks are nested to produce different responses and to follow and execute deeper paths as paths and parameters are matched.
PROJECT MAINTENANCE RESUMES
Bullet becomes an active project again. Currently there's a changing of the guard. Feel free to further use and contribute to the framework.
Requirements
- PHP 5.6+ (PHP 7.1 recommended)
- Composer for all package management and autoloading (may require command-line access)
Rules
- Apps are built around HTTP URIs and defined paths, not forced MVC (but MVC-style separation of concerns is still highly recommenended and encouraged)
- Bullet handles one segment of the path at a time, and executes the callback for that path segment before proceesing to the next segment (path callbacks are executed from left to right, until the entire path is consumed).
- If the entire path cannot be consumed, a 404 error will be returned
(note that some callbacks may have been executed before Bullet can
know this due to the nature of callbacks and closures). Example: path
/events/45/edit
may return a 404 because there is noedit
path callback, but pathsevents
and45
would have already been executed before Bullet can know to return a 404. This is why all your primary logic should be contained inget
,post
, or other method callbacks or in the model layer (and not in the barepath
handlers). - If the path can be fully consumed, and HTTP method handlers are present in the path but none are matched, a 405 "Method Not Allowed" response will be returned.
- If the path can be fully consumed, and format handlers are present in the path but none are matched, a 406 "Not Acceptable" response will be returned.
Advantages
-
Super flexible routing. Because of the way the routing callbacks are nested, Bullet's routing system is one of the most flexible of any other PHP framework or library. You can build any URL you want and respond to any HTTP method on that URL. Routes are not restricted to specific patterns or URL formats, and do not require a controller with specific method names to respond to specific HTTP methods. You can nest routes as many levels deep as you want to expose nested resources like
posts/42/comments/943/edit
with a level of ease not found in most other routing libraries or frameworks. - Reduced code duplication (DRY). Bullet takes full advantage of its nested
closure routing system to reduce a lot of typical code duplication required
in most other frameworks. In a typical MVC framework controller, some code
has to be duplicated across methods that perform CRUD operations to run ACL
checks and load required resources like a Post object to view, edit or delete.
With Bullet's nested closure style, this code can be written just once in a
path or param callback, and then you can
use
the loaded object in subsequent path, param, or HTTP method handlers. This eliminates the need for "before" hooks and filters, because you can just run the checks and load objects you need before you define other nested paths anduse
them when required.
Installing with Composer
Use the basic usage guide, or follow the steps below:
Setup your composer.json
file at the root of your project
Install Composer
curl -s http://getcomposer.org/installer | php
Install Dependencies (will download Bullet)
php composer.phar install
Create index.php
(use the minimal example below to get started)
This application can be placed into your server's document root. (Make sure it
is correctly configured to serve php applications.) If index.php
is in the
document root on your local host, the application may be called like this:
http://localhost/index.php?u=/
and
http://localhost/index.php?u=/foo
If you're using Apache, use an .htaccess
file to beautify the URLs. You need
mod_rewrite to be installed and enabled.
<IfModule mod_rewrite.c>
RewriteEngine On
# Reroute any incoming requestst that is not an existing directory or file
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?u=$1 [L,QSA,B]
</IfModule>
With this file in place Apache will pass the request URI to index.php
using
the $_GET['u'] parameter. This works in subdirectories as expected i.e. you
don't have to explicitly take care of removing the path prefix e.g. if you use
mod_userdir, or just install a Bullet application under an existing web app to
serve an API or simple, quick dynamic pages. Now your application will answer to these pretty urls:
http://localhost/
and
http://localhost/foo
NGinx also has a rewrite
command, and can be used to the same end:
server {
# ...
location / {
# ...
rewrite ^/(.*)$ /index.php?u=/$1;
try_files $uri $uri/ =404;
# ...
}
# ...
}
If the Bullet application is inside a subdirectory, you need to modify the
rewrite
line to serve it correctly:
server {
# ...
location / {
rewrite ^/bulletapp/(.*)$ /bulletapp/index.php?u=/$1;
try_files $uri $uri/ =404;
}
# ...
}
Note that if you need to serve images, stylesheets, or javascript too, you
need to add a location
for the static root directory without the reqrite
to avoid passing those URLs to index.php.
View it in your browser!
Syntax
Bullet is not your typical PHP micro framework. Instead of defining a full
path pattern or a typical URL route with a callback and parameters mapped
to a REST method (GET, POST, etc.), Bullet parses only ONE URL segment
at a time, and only has two methods for working with paths: path
and
param
. As you may have guessed, path
is for static path names like
"blog" or "events" that won't change, and param
is for variable path
segments that need to be captured and used, like "42" or "my-post-title".
You can then respond to paths using nested HTTP method callbacks that
contain all the logic for the action you want to perform.
This type of unique callback nesting eliminates repetitive code for loading records, checking authentication, and performing other setup work found in typical MVC frameworks or other microframeworks where each callback or action is in a separate scope or controller method.
Capturing Path Parameters
Perhaps the most compelling use of URL routing is to capture path
segments and use them as parameters to fetch items from a database, like
/posts/42
and /posts/42/edit
. Bullet has a special param
handler
for this that takes two arguments: a test
callback that validates the
parameter type for use, and and a Closure
callback. If the test
callback returns boolean false
, the closure is never executed, and the
next path segment or param is tested. If it returns boolean true
, the
captured parameter is passed to the Closure as the second argument.
Just like regular paths, HTTP method handlers can be nested inside param callbacks, as well as other paths, more parameters, etc.
Returning JSON (Useful for PHP JSON APIs)
Bullet has built-in support for returning JSON responses. If you return
an array from a route handler (callback), Bullet will assume the
response is JSON and automatically json_encode
the array and return the
HTTP response with the appropriate Content-Type: application/json
header.
HTTP Response Bullet Sends:
Content-Type:application/json
Bullet Response Types
There are many possible values you can return from a route handler in
Bullet to produce a valid HTTP response. Most types can be either
returned directly, or wrapped in the $app->response()
helper for
additional customization.
Strings
Strings result in a 200 OK response with a body containing the returned
string. If you want to return a quick string response with a different
HTTP status code, use the $app->response()
helper.
Booleans
Boolean false
results in a 404 "Not Found" HTTP response, and boolean
true
results in a 200 "OK" HTTP response.
Integers
Integers are mapped to their corresponding HTTP status code. In this example, a 418 "I'm a Teapot" HTTP response would be sent.
Arrays
Arrays are automatically passed through json_encode
and the appropriate
Content-Type: application/json
HTTP response header is sent.
Templates
The $app->template()
helper returns an instance of
Bullet\View\Template
that is lazy-rendered on __toString
when the
HTTP response is sent. The first argument is a template name, and the
second (optional) argument is an array of parameters to pass to the
template for use.
Serving large responses
Bullet works by wrapping every possible reponse with a Response object. This would normally mean that the entire request must be known (~be in memory) when you construct a new Response (either explicitly, or trusting Bullet to construct one for you).
This would be bad news for those serving large files or contents of big database tables or collections, since everything would have to be loaded into memory.
Here comes \Bullet\Response\Chunked
for the rescue.
This response type requires some kind of iterable type. It works with regular arrays or array-like objects, but most importatnly, it works with generator functions too. Here's an example (database functions are purely fictional):
The $g
variable will contain a Closure that uses yield
to fetch, process,
and return data from a big dataset, using only a fraction of the memory needed
to store all the rows at once.
This results in a HTTP chunked response. See https://tools.ietf.org/html/rfc7230#section-4.1 for the technical details.
HTTP Server Sent Events
Server sent events are one way to open up a persistent channel to a web server, and receive notifications. This can be used to implement a simple webchat for example.
This standard is part of HTML5, see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events for details.
The example below show a simple application using the fictional send_message and receive_message functions for communications. These can be implemented over various message queues, or simple named pipes.
The SSE response uses chunked encoding, contrary to the recommendation in the standard. We can do this, since we tailoe out chunks to be exactly message-sized.
This will not confuse upstream servers when they see no chunked encoding, AND no Content-Length header field, and might try to "fix" this by either reading the entire response, or doing the chunking on their own.
PHP's output buffering can also interfere with messaging, hence the call to \Bullet\Response\Sse::cleanupOb(). This method flushes and ends every level of output buffering that might present before sending the response.
The SSE response automatically sends the X-Accel-Buffering: no
header to
prevent the server from buffering the messages.
Nested Requests (HMVC style code re-use)
Since you explicitly return
values from Bullet routes instead of
sending output directly, nested/sub requests are straightforward and easy.
All route handlers will return Bullet\Response
instances (even if they
return a raw string or other data type, they are wrapped in a response
object by the run
method), and they can be composed to form a single
HTTP response.
Running Tests
To run the Bullet test suite, simply run vendor/bin/phpunit
in the
root of the directory where the bullet files are in. Please make sure
to add tests and run the test suite before submitting pull requests for
any contributions.
Credits
Bullet - and specifically path-based callbacks that fully embrace HTTP and encourage a more resource-oriented design - is something I have been thinking about for a long time, and was finally moved to create it after seeing @joshbuddy give a presentation on Renee (Ruby) at Confoo 2012 in Montréal.