-
Notifications
You must be signed in to change notification settings - Fork 0
Slim Framework Documentation
- Overview
- Initialize Slim
- RESTful Routes
- The Request Object
- The Response Object
- Sessions
- Views
- Before and After Callbacks
- Error Handling
Slim lets you build a complete PHP web service with only a single PHP file. It's quite simple. The typical process for writing a Slim application is:
//Require Slim
require('slim/Slim.php');
//Initialize Slim
Slim::init();
//Define routes
Slim::get('/books/:id', function ($id) {
//Show book with id = $id
});
//Run Slim
Slim::run();
The first thing you must do is require() Slim into your bootstrap file. If you move the slim/ directory elsewhere on your file system, it is important that you keep Slim's dependencies in the same directory as Slim.php. Keeping the files together enables you to only require Slim.php and have the other files required automatically for you. Assuming the slim/ directory is on your include path, you only need to call:
require('slim/Slim.php');
After you require Slim, you need to initialize Slim. Initializing Slim instantiates a new Slim app behind the scenes. To initialize Slim:
Slim::init();
If you will use a custom View to render templates, you can set your custom View and initialize Slim at the same time. Let's pretend I have a custom View class called TwigView. I would pass the name of my custom View, "TwigView", into the Slim::init() method like this:
Slim::init('TwigView');
It is important that you only initialize Slim once.
Slim supports RESTful routing, allowing you to route a URL to a specific callback function. Slim also associates each route with a specific HTTP request method (GET, POST, PUT, or DELETE).
Slim will execute the first route that matches the current request. Slim first finds all routes that match the current request's method, then it examines each of these routes in the order they were added. The first matching route's callback function will then be run.
Use Slim::get() to associate a callback function with a GET request URI.
//For PHP 5 >= 5.3
Slim::get('/books/:id', function ($id) {
//Show book with id = $id
});
//For PHP 5 < 5.3
Slim::get('/books/:id', 'show_book');
function show_book($id) {
//Show book with id = $id
}
In this example, a GET request for "/books/1" will execute the associated function, passing "1" into the function as the first parameter.
Use Slim::post() to associate a callback function with a POST request URI.
//For PHP 5 >= 5.3
Slim::post('/books', function () {
//Create a new book
});
//For PHP 5 < 5.3
Slim::post('/books', 'post_book');
function post_book() {
//Create a new book
}
In this example, a POST request for "/books" will execute the associated function.
Use Slim::put() to associate a callback function with a PUT request URI.
//For PHP 5 >= 5.3
Slim::put('/books/:id', function ($id) {
//Update book with id = $id
});
//For PHP 5 < 5.3
Slim::put('/books/:id', 'put_book');
function put_book($id) {
//Update book with id = $id
}
In this example, a PUT request for "/books/1" will execute the associated function and update the book with the specified ID.
Unfortunately, modern browsers do not provide native support for PUT requests. To work around this limitation, ensure your HTML form's method is "post", then add a method override parameter to your HTML form like this:
<form action="/books/1" method="post">
... other form fields here...
<input type="hidden" name="_METHOD" value="PUT"/>
<input type="submit" value="Update Book"/>
</form>
Use Slim::delete() to associate a callback function with a DELETE request URI.
//For PHP 5 >= 5.3
Slim::delete('/books/:id', function ($id) {
//Delete book with id = $id
});
//For PHP 5 < 5.3
Slim::delete('/books/:id', 'delete_book');
function delete_book($id) {
//Delete book with id = $id
}
In this example, a DELETE request for "/books/1" will execute the associated function and delete the book with the specified ID.
Unfortunately, modern browsers do not provide native support for DELETE requests. To work around this limitation, ensure your HTML form's method is "post", then add a method override parameter to your HTML form like this:
<form action="/books/1" method="post">
... other form fields here...
<input type="hidden" name="_METHOD" value="DELETE"/>
<input type="submit" value="Delete Book"/>
</form>
As you may have noticed above, you can embed parameters into your routes. In this example, I have two parameters in my route, ":one" and ":two".
//For PHP 5 >= 5.3
Slim::get('/books/:one/:two', function ($one, $two) {
echo "The first paramter is " . $one;
echo "The second parameter is " . $two;
});
//For PHP 5 < 5.3
Slim::get('/books/:one/:two', 'callback_name');
function callback_name($one, $two) {
echo "The first paramter is " . $one;
echo "The second parameter is " . $two;
}
To create a URL parameter, simple prepend ":" to the parameter name in the route pattern. When the route is matched to the current request, the values for each route parameter are passed into the associated callback function, in order of appearance.
Slim lets you assign conditions to route parameters. If the specified conditions are not met, the route is not run. For example, if you needed a route whose second segment must be a valid 4-digit year, you could enforce this condition like this:
Slim::get('/archive/:year', function ($year) {
echo "You are viewing archives from $year";
})->conditions(array('year' => '(19|20)\d\d'));
You only need to call the conditions method passing in an associative array whose keys match any of the route's parameters, and whose values are regular expressions.
Slim also lets you assign a name to a route. Naming a route enables you to dynamically generate URLs using the Slim::urlFor helper method. When you use the Slim::urlFor helper method to create application URLs, you can freely change route patterns without breaking your application. Here is an example of a named route:
Slim::get('/hello/:name', function ($name) {
echo "Hello, $name!";
})->name('hello');
You may now generate URLs for this route using the Slim::urlFor helper method, described next. If you need to assign a name and conditions to a route, you can chain your method calls like this:
Slim::get('/hello/:name', function ($name) {
echo "Hello, $name!";
})->name('hello')->conditions(array('name' => '\w+'));
As described in the Named Routes section above, this helper method lets you dynamically create URLs for a named route so that, were a route pattern to change, your URLs would update automatically without breaking your application. This example demonstrates how to generate URLs for the named route above:
$url = Slim::urlFor(
'hello',
array('name' => 'Josh')
);
//$url == '/hello/Josh'
To use this helper method, you must first assign a name to a route. Next, call Slim::urlFor(). The first parameter is the name of the route, and the second parameter is an associative array used to replace the route's URL parameters with actual values.
A route can tell the Slim application to continue to the next matching route with Slim::pass(). When this method is invoked, the Slim application will immediately stop processing the current route and invoke the next matching route. If no subsequent matching route is found, a 404 Not Found response is sent to the client. Here is an example:
Slim::get('/foo', function () {
Slim::pass();
});
It is easy to redirect the client to another URL with the Slim::redirect() method. To issue a temporary redirect, call Slim::redirect() and set the first method parameter to the destination URL:
Slim::post('/users', function () {
//Create new user here
Slim::redirect('/users-list');
});
Or if you wish to issue a permanent redirect, you must specify the destination URL as the first parameter and the HTTP status code as the second parameter:
Slim::post('/users', function () {
//Create new user here
Slim::redirect('/users-list', 301);
});
This method will automatically set the necessary HTTP Location header and status code and immediately send the redirect HTTP response to the client.
It is an inevitability that someone will request a page that does not exist. Slim lets you easily define a custom Not Found handler with Slim::notFound(). The Not Found handler will be invoked when a matching route is not found for the current HTTP request. This method may be invoked in two different contexts.
If you invoke Slim::notFound() and specify a callable object as its first parameter, this method will register the callable object as the Not Found handler. However, the registered handler will not be invoked.
//For PHP 5 >= 5.3
Slim::notFound(function () {
Slim::render('404.html');
});
//For PHP 5 < 5.3
Slim::notFound('custom_not_found_callback');
function custom_not_found_callback() {
Slim::render('404.html');
}
If you invoke Slim::notFound() without any parameters, this method assumes you wish to invoke a previously registered Not Found handler.
Slim::get('/hello/:name', function ($name) {
if( $name === 'Waldo' ){
Slim::notFound();
} else {
echo "Hello, $name";
}
});
A Slim application has a Request object that provides details about the current HTTP request. This Request object determines how your Slim application will run: it provides the HTTP request method and the HTTP request URI among other things. To access the Request object, you can call:
$request = Slim::request();
NOTE You will typically use the Request object inside a Route's callback function.
An HTTP request may have associated parameters (not to be confused with Route parameters above). To access the request parameters, you can call the Request object like this:
$paramValue = Slim::request()->params('paramName');
This method will first search PUT parameters, then POST parameters, then GET parameters. If no parameter is found, NULL is returned. If you only wish to search for a specific type of parameter, you can use these methods instead:
//GET parameter
$paramValue = Slim::request()->get('paramName');
//POST parameter
$paramValue = Slim::request()->post('paramName');
//PUT parameter
$paramValue = Slim::request()->put('paramName');
If a parameter does not exist, each method above will return NULL rather than throwing an error. You can also call each function above without a parameter name to get an array of all parameters.
$allGetParams = Slim::request()->get();
$allPostParams = Slim::request()->post();
$allPutParams = Slim::request()->put();
The Request object can tell you more about the HTTP request.
//Get the request URI
$uri = Slim::request()->resource;
//Get the request method: GET, POST, PUT, or DELETE
$method = Slim::request()->method;
//Is this an AJAX request?
$isAjax = Slim::request()->isAjax;
A Slim application also has a Response object that will ultimately be returned to the client after your application runs. The Response object contains three important features: the HTTP status code (ie. 200 OK), the response headers (ie. Content-Length), and the response body. Just as you access the Request object, you can also access the Response object:
$response = Slim::response();
Change the Response status to change the type of response sent to the client. If you never touch the Response object, and if your code runs without issue, then the Response status will default to 200. If the Slim app cannot find a route to match the current request, the Response status will be 404. Or you can manually set the Response status with:
Slim::response()->status(200);
Pass in the numeric HTTP status code as a parameter. If you want to retrieve the current Response status, you can call the same method without passing in a parameter.
NOTE Normally, you won't manually set the Response status. There are other helper methods that will do this for you, such as `Slim::error()` (See [Error Handling](#errors)).
You can also add custom headers to the Response object:
Slim::response()->header('Content-Length', '200');
If you want to retrieve a header, you can call:
$length = Slim::response()->header('Content-Length');
Or if you want an array of all Response object headers:
Slim::response()->headers();
The Response headers are, for the most part, set automatically requiring no effort on your part. But just know that you can customize the Response object headers if you need to.
Anything you echo() within a Route callback function will be appended to the Response body. It's that simple. If you need to manipulate the Response body in custom Middleware, you can call:
//Append the Response body
Slim::response()->write('More body content');
//Overwrite the Response body
Slim::response()->body('New body content');
Slim lets you store persistent session variables that will be accessible across multiple HTTP requests with Slim::session(). Session variables will remain available until the variable expires or is cleared. Slim's session implementation is built on top of browser cookies; therefore, each session variable's value may not be larger then 4KB in size.
Slim::session() acts as both a getter and a setter. If you invoke Slim::session() and specify only the first parameter, this will return the value of the cookie with the specified name, or NULL if said cookie does not exist. If you invoke Slim::session() with two or more parameters, this method will create a new Cookie with the given name, value, and other options. If a Cookie with the same name already exists, that cookie will be overwritten when the Response is sent to the client.
To "delete" a Session variable, create a new Session variable with the same name and set its value to FALSE, NULL, or an empty string. Here are some examples of Slim session variables.
//Get a cookie value
$value = Slim::session('name');
//Set cookie value
Slim::session('name', 'value');
Slim::session() has the same method signature as PHP's setcookie() function. So you could set a session variable like this:
//Set a cookie value for a specific domain with HTTPS
Slim::session('name', 'value', time()+3600, '/', 'domain.com', true, true);
A View is a PHP class that renders a template. You can use a View to render a template within a Route callback function.
//For PHP >= 5.3
Slim::get('/books/:id', function ($id) {
Slim::render('myTemplate.php', array('id' => $id));
});
//For PHP < 5.3
Slim::get('/books/:id', 'show_book');
function show_book($id) {
Slim::render('myTemplate.php', array('id' => $id));
}
If you need to pass data from the Route callback function to the View, you must explicitly do so by passing an array as the second parameter of Slim::render(), like this:
Slim::render(
'myTemplate.php',
array( 'name' => 'Josh' )
);
You can also set the Response status when you render a template:
Slim::render(
'myTemplate.php',
array( 'name' => 'Josh' ),
404
);
Slim's default View includes the requested template with include(). The included template will have access to any data passed by the Slim::render() method. Although this basic View works, it's not very powerful. Hence, custom Views…
A custom View is a PHP class that extends View and implements one method — render(). The custom View's render method is passed the name of the template as its one and only function parameter.
class CustomView extends View {
public function render( $template ) {
echo('The final rendered template');
}
}
The custom View can do whatever it wants, so long as it ultimately echoes the template's rendered output using echo(). A custom View makes it easy to integrate popular PHP templating systems, like Twig or Smarty.
The View class will have access to any data passed to it by the Slim::render() method. The View can access this data array with $this->data. Here is an example.
Slim::get('/books/:id', function ($id) {
Slim::render('show.php', array('title' => 'Sahara'));
});
class CustomView extends View {
public function render( $template ) {
//$template == 'show.php'
//$this->data['title'] == 'Sahara'
}
}
NOTE Use the `Slim::root()` method to find the absolute path to the Slim application's root directory. This can be helpful when resolving paths to template files!
To use your custom View, you must require the custom View class before you initialize Slim. Then you must tell Slim to use your custom View.
require('slim/Slim.php');
require('customView.php');
//Pass the *name* of the custom View class
Slim::init('CustomView');
To pass data into a View for use in your templates, use the Slim::view()->data() method. This method accepts an associative array as it's first and only parameter. The array keys are the template variable names, and the array values are the template variable values.
This method will not overwrite previously set data. Instead, it will merge the new data with existing data. This way you can set data (ie. the current user object or logged in status) in a before callback and set route-specific data in the appropriate route callback.
Slim::before(function () {
Slim::view()->data(array('loggedIn' => true));
});
Slim::get('/account', function () {
Slim::render('ordersTemplate.php', array('orders' => $orders));
});
In this example, your ordersTemplate.php template will have access to both loggedIn and orders variables.
Let's face it: sometimes things go wrong. But it is important that you intercept errors and respond to them appropriately. Slim provides several helper methods to help you respond to errors.
The most common method you will use to respond to errors is Slim::raise(). This method accepts two parameters: the HTTP status code and an optional message.
//Send a default 500 error response
Slim::raise(500);
//Send a 403 Forbidden response
Slim::raise(403, 'You shall not pass');
This method will override the current Response body and Response status code, and then immediately send the new Response to the client. If you would like to render a template to display error messages, you should instead call:
Slim::render(
'errorTemplate.php',
array( 'error' => 'Permission Denied'),
403
);
If your Slim application throws an exception or triggers an error, a nice error page will be displayed with details about the exception or error including the error message, the file path, the line number, and a stack trace if available.
This method does what it says. It immediately stops the Slim application and sends the response as-is to the client. No ifs, ands, or buts.