Skip to content

Slim Framework Documentation

codeguy edited this page Sep 29, 2010 · 75 revisions

Slim Framework Documentation

Table of Contents

Overview

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();

Require Slim

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');

Back to Top

Initialize Slim

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.

Back to Top

Routing

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.

Slim::get()

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.

Slim::post()

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.

Slim::put()

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>

Slim::delete()

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>

Slim::notFound()

It is an inevitability that someone will request a page that does not exist. This method let's you define a callback function to run if the current request does not have a matching route.

//For PHP 5 >= 5.3
Slim::notFound(function () {
	echo 'Oops! Page not found.';
});

//For PHP 5 < 5.3
Slim::notFound('custom_not_found_callback');
function custom_not_found_callback() {
	echo 'Oops! Page not found.';
}

Back to Top

Route Parameters

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.

Back to Top

Route Conditions

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.

Back to Top

Named Routes

Slim also lets you assign a name to a route. Naming a route enables you to dynamically generate URLs using the Router::urlFor helper method. When you use the Router::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 Router::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+'));

Back to Top

URL Helper

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::router()->urlFor(
	'hello',
	array('name' => 'Josh')
);
//$url == '/hello/Josh'

NOTE To access the Slim router, call Slim::router()

To use this helper method, you must first assign a name to a route. Next, call the router's urlFor helper method. 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.

Back to Top

The Request Object

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.

Request Params

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:

//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();

Request Attributes

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;

Back to Top

The Response Object

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();

Response Status

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)).

Response Headers

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.

Response Body

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');

Response Cookies

Setting Response cookies is simple and uses the same signature as PHP's setcookie() function.

//Set a cookie
Slim::response()->setCookie($name, $value, $expires, $path, $domain, $secure, $httpOnly);

//Or, remove a cookie
Slim::response()->deleteCookie($name);

Back to Top

Views

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…

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.

The Route

Slim::get('/books/:id', function ($id) {
	Slim::render('show.php', array('title' => 'Sahara'));
});

The View

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');

Back to Top

Error Handling

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.

Slim::raise()

The most common method you will use to respond to errors is Slim::raise(). This method accepts two parameters: a message and a Response status code — the message is required and the status defaults to 500.

//Send a default 500 error response
Slim::raise('Something went wrong');

//Send a 403 Forbidden response
Slim::raise('You are forbidden', 403);

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 nice template to display error messages, you can instead call:

Slim::render(
	'errorTemplate.php',
	array( 'error' => 'Permission Denied'),
	403
);
Slim::stop();

Throwing Exceptions

If your Slim application throws a non-Fatal exception, that exception will be caught, the Response body will be the Exception message, and the Response status code will be 500. The Response will be sent to the client immediately after the Exception is caught.

Slim::stop()

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.

Back to Top

Clone this wiki locally