Skip to content

Slim Framework Documentation

codeguy edited this page Dec 12, 2010 · 78 revisions

Documentation

Table of Contents

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

Application Settings

A Slim application can be customized with configuration settings using Slim::config(). For example, you can use Slim::config() to enable or disable logging, show or hide errors screens, and define your log and templates directories. Although there are several built-in Slim application settings (see below), you are free to define your own custom settings as you need.

Define a setting

Slim::config('foo', 'bar');

If you need to define a lot of application settings, you can do so at once by passing an associative array, like this:

Slim::config(array(
	'one' => 'A',
	'two' => 'B',
	'three' => 'C'
));

Retrieve a Setting

$settingValue = Slim::config('foo'); //returns 'bar'

If the requested setting does not exist, Slim::config() returns NULL instead.

Built-in Settings

Slim sets several settings automatically when you initialize your Slim application. These settings are:

log
Boolean. Should Slim enable application logging? Default: TRUE.
log_dir
String. Absolute or relative path to the log files directory. Default: ./logs (relative to bootstrap.php)
debug
Boolean. Should Slim display detailed errors screens for debugging? If FALSE, Slim will instead invoke your custom Error handler if available to display a visitor-friendly error screen. Default: TRUE.
templates_dir
String. Absolute or relative path to the templates directory. This defines the root directory used by the View class to lookup template files. Default: ./templates(relative to bootstrap.php).

It is important that you define your application settings immediately after you initialize the Slim application

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>

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

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

Back to Top

Passing

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

Back to Top

Redirects

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.

Back to Top

Custom 404 Page

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.

When defining the Not Found handler

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

When invoking the Not Found callback

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";
	}
});

Back to Top

Trailing Slashes and Routing

Slim routes automatically provide pretty URLs and intelligent redirection — behavior very similar to the Apache web server. Here are two example routes:

Slim::get('/services/', function () {

});

Slim::get('/contact', function () {

});

At first glance, both routes appear similar. However, in the first route example, the canonical URL for the services route has a trailing slash. It acts the same as a folder; accessing it without a trailing slash will prompt Slim to redirect to the canonical URL with the trailing slash.

In the second example, the URL is defined without a trailing slash. Therefore, it behaves similar to a file. Accessing it with a trailing slash will cause a 404 Not Found error.

Why did I choose this behavior? This allows relative URLs to continue working if users access the page and forget the trailing slash. This is consistent with Apache's behavior. URLs will also stay unique, and search engines should not index the same page twice with different URLs.

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:

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

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

Back to Top

HTTP Caching

Slim provides built-in support for HTTP caching. It is very simple to cache a resource using Slim::etag() or Slim::lastModified(). It is best to use one of these methods per route — not both. Both of these methods will instruct the browser client to cache the resource client-side. More details for each method are below. It is important that you call Slim::etag() or Slim::lastModified() in your route callback before any other code so that Slim can avoid unnecessary processing.

ETag HTTP Caching

Slim provides built-in support for HTTP caching using ETags. An ETag is a unique identifier for a resource URL. When an ETag header is set with Slim::etag(), the browser client will send an If-None-Match header with each subsequent request for the same URL. If the ETag you define for the resource URL matches the If-None-Match request header, Slim will return a 304 Not Modified response which will prompt the browser client to use its cache; this also prevents Slim from serving the entire markup for the resource URL saving bandwidth and response times.

Setting an ETag with Slim is very simple. You only need to call Slim::etag() in your route callback, passing in a unique ID as the first and only argument.

Slim::get('/foo', function (){
	Slim::etag('unique-id');
	echo "This will be cached after the initial request!";
});

That's it. You only need to make sure the unique ETag ID is unique for the given route/resource. Also make sure the ETag unique ID changes as your route resource changes; otherwise, the browser client will continue serving its outdated cache.

LastModified HTTP Caching

Slim provides built-in support for HTTP caching using resource's last modified date. When you specify a last modified date, Slim tells the browser client the last date and time the current resource was modified. The browser client will then send a If-Modified-Since header with each subsequent request for the given resource URL. If the last modification date you specify matches the If-Modified-Since request header, Slim will return a 304 Not Modified response which will prompt the browser client to use its cache; this also prevents Slim from serving the entire markup for the resource URL saving bandwidth and response times.

Setting a last modified with Slim is very simple. You only need to call Slim::lastModified() in your route callback passing in a UNIX timestamp that represents the last modification date for the given route/resource. Be sure the Slim::lastModified() timestamp updates along with the route resource's last modification date; otherwise, the browser client will continue serving its outdated cache.

Slim::get('/foo', function (){
	Slim::lastModified(1286139652);
	echo "This will be cached after the initial request!";
});

Back to Top

Sessions (Deprecated in v1.1... see "Cookies" below)

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

Back to Top

Cookies (Develop Branch Only)

Getting Cookies

Slim provides easy-to-use Cookie management with Slim::getCookie() and Slim::setCookie(). Assume a Cookie exists with name foo and value bar. This Cookie already exists in the web browser cache and is passed to the Slim application within the HTTP request. We can retrieve the Cookie value like this:

$value = Slim::getCookie('foo');
//$value === 'bar'

If you attempt to retrieve a Cookie that does not exist, NULL is returned.

$value = Slim::getCookie('doesNotExist');
//$value === NULL

Notice that Slim::getCookie() will return the value of the Cookie. If you need to obtain the internal Cookie object for a Cookie set during the current request, you should use Slim::request()->getCookie() instead.

Slim::setCookie('foo', 'bar');
$cookie = Slim::response()->getCookie('foo');
$cookieClass = get_class($cookie);
//$cookieClass === 'Cookie'

Feel free to explore the cookie-related methods in class Response and Cookie for interacting with the actual Cookie objects.

Setting Cookies

It is also very easy to set a Cookie with Slim. This example sets a Cookie with name newCookie and value newCookieValue.

Slim::setCookie('newCookie', 'newCookieValue');

This will assign a new Cookie to the Response object that will be returned to the client. The Cookie will be accessible to Slim::getCookie() in the subsequent HTTP request.

Notice how we only specified a name and a value. What if we wanted to set a specific expiration time for the Cookie? There are several ways to do this:

//Cookie will expire one hour from now
Slim::setCookie('newCookie', 'newCookieValue', 3600);

In the above example, we set the expiration time as 3600 seconds from now. If the third argument is an integer (and greater than 0), the argument is considered to be the number of seconds from now when the Cookie will expire.

//Cookie will expire one hour from now
Slim::setCookie('newCookie', 'newCookieValue', '1 hour');

In the above example, we set the expiration time as '1 hour' from now. If the third argument is a string, it is parsed with strtotime() and determines the amount of time from now when the Cookie will expire.

//Cookie will expire when session expires
Slim::setCookie('newCookie', 'newCookieValue', 0);

In the above example, we set the expiration time as 0. If the third argument is 0 (an integer), then the Cookie will expire when the client session ends (usually when the website visitor closes his or her browser).

//Cookie with all possible attributes
Slim::setCookie(
	'newCookie',		//name
	'newCookieValue',	//value
	'1 hour',			//expiration from now
	'/',				//path
	'joshlockhart.com',	//domain
	true,				//secure?
	true				//http only?
);

Configure Cookies

As shown above, a default Cookie expiration time will be used if you do not provide an expiration time in Slim::setCookie(). To configure the default Cookie expiration time, do so in Slim::config() like this:

Slim::config('cookies.expire_after', '20 minutes');

If you do not explicitly set your own expiration time in Slim::config(), the default Cookie lifetime is 20 minutes.

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

Templates Directory

By default, the built-in View class and all custom View classes will look for template files in the ./templates directory, relative to the bootstrap.php file. You can easily change the templates directory by setting the application templates setting with:

Slim::config('templates_dir', '/path/to/templates');

Be sure you specify your custom templates directory immediately after initializing your Slim application. This setting will be available in your View class by calling:

$this->templatesDirectory();

Back to Top

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

It is also possible to pass a custom View object instance into Slim::init, rather than just the name of the custom View class. This may be helpful if your custom View requires special preparation.

$myView = new CustomView();
Slim::init($myView);

Back to Top

Setting View Data

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.

Back to Top

Plugins

Slim provides a hook plugin architecture, allowing you to register callable objects to be invoked at specific moments in the Slim application lifecycle. All hooks may access and interact with the Request, Response, Router, and View objects.

Plugins are only available in the DEVELOP branch until version 1.1 is officially released

Plugin Hooks

The available hooks within a Slim application are:

slim.before

This hook is invoked before the Slim application is run and before output buffering is turned on. This hook is invoked once during the Slim application lifecycle.

slim.before.router

This hook is invoked after output buffering is turned on and before the router is dispatched. This hook is invoked once during the Slim application lifecycle.

slim.before.dispatch

This hook is invoked before the current matching route is dispatched. Usually this hook is invoked only once during the Slim application lifecycle; however, this hook may be invoked multiple times if a matching route chooses to pass to a subsequent matching route.

slim.after.dispatch

This hook is invoked after the current matching route is dispatched. Usually this hook is invoked only once during the Slim application lifecycle; however, this hook may be invoked multiple times if a matching route chooses to pass to a subsequent matching route.

slim.after.router

This hook is invoked after the router is dispatched, before the Response is sent to the client, and before output buffering is turned off. This hook is invoked once during the Slim application lifecycle.

slim.after

This hook is invoked after output buffering is turned off and after the Response is sent to the client. This hook is invoked once during the Slim application lifecycle.

Registering a callable object for a hook

To register a callable object for a given hook:

Slim::hook('slim.before.dispatch', function () {
	echo 'Prepare to dispatch!';
});

The first argument is the hook name, and the second argument is a callable object (ie. an anonymous function, a function name, or an array whose elements specify a class/object and method to call).

Each hook maintains an array of registered objects. When the hook is invoked, each of its registered objects is called in the order registered.

Creating new hooks

You may create new hooks to be invoked within the context of your own plugin. To create a new hook, insert the following code within your plugin. This code will call all objects registered for the specified hook name.

Slim::hook('my.new.hook.name');

The first and only argument should be the name of your new hook. Nothing prevents you from overwriting an existing hook, so it is recommended that you namespace your hooks with a unique prefix:

Slim::hook('myplugin.new.hook.name');

Distributing plugins

A plugin should adhere to this directory structure:

thePluginName/
	README
	ThePluginName.php
	lib/

A plugin should have its own directory, a README file, and a primary PHP script. The README file should provide, at minimum, the following information:

  • Plugin name
  • Plugin version
  • Plugin URL
  • Plugin author
  • Plugin description
  • Plugin usage

The primary PHP script, "ThePluginName.php" in the example above, should do all that is required to initialize and register the plugin with a Slim application. If a plugin has more than one PHP script, place other PHP scripts inside of a lib/ directory.

If a plugin requires more advanced setup, provide detailed instructions for doing so in the plugin's README file.

Installing plugins

To "install" a Slim plugin, you only need to require the plugin's primary PHP script into your Slim application's bootstrap.php file. It is important that you require plugin files after the Slim application has been initialized.

require 'slim/Slim.php';
Slim::init();
require 'plugins/thePluginName/ThePluginName.php';

Example Plugins

Authentication

This is a very basic example, but it demonstrates how you may approach authentication within your Slim application.

<?php
/**
 * MyPlugin.php
 */
Slim::hook('slim.before.dispatch', function () {
	$request = Slim::request();
	$currentRoute = Slim::router()->current();
	if ( preg_match('@^users/@', $currentRoute->pattern) ) {
		//Authenticate current user or redirect to login page
	}
});
?>

Appending new routes

This example appends routes to an existing Slim application. This demonstrates how you can package routes and other complex functionality into a single plugin and easily integrate it within an existing Slim application.

<?php
/**
 * MyPlugin.php
 */
Slim::hook('slim.before', function () {
	Slim::get('/login', function () {
		//Render login form
	});
	Slim::post('/login', function () {
		//Log in user
	});
});
?>

Logging

Slim supports logging out of the box. By default, logging is enabled. You can enable or disable Slim logging with:

//Enable logging
Slim::config('log', true);

//Disable logging
Slim::config('log', false);

You should also specify the log files directory. Slim will write a unique log file per day into this directory. By default, Slim will write log files to ./logs (relative to bootstrap.php). You may define a custom log file directory with:

Slim::config('log_dir', '/path/to/log/directory');

Slim will automatically log application errors and exceptions. You can also manually write to the log file with:

Slim::log('This is the log message', Slim::ERROR);

The first argument is the log message (required), and the second argument is the type of log message (optional). Possible message types are:

Slim::ERROR
Slim::WARNING
Slim::NOTICE

As stated in the Application Settings section, you should always define your application settings immediately after initializing your Slim application.

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::halt()

A common method used to respond to errors is Slim::halt(). This method accepts two parameters: the HTTP status code and an optional message.

//Send a default 500 error response
Slim::halt(500);

//Send a 403 Forbidden response
Slim::halt(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
);

Slim::halt() may send any type of Response to the client: informational, success, redirect, not found, client error, or server error.

Slim::error()

This method allows you to specify a custom error handler that will be invoked when an error or exception occurs and debugging is disabled (if debugging is enabled, a developer-oriented error message will appear instead). This handler should ideally render a visitor-friendly page that explains an error occurred. Similar to Slim::notFound(), this method acts as both a getter and a setter.

Setting the Error handler

//PHP 5 >= 5.3
Slim::error(function () {
	Slim::render('error.php');
});

//PHP 5 < 5.3
Slim::error('custom_error_handler');
function custom_error_handler(){
	Slim::render('error.php');
}

Invoking the Error handler

Slim will automatically invoke your error handler if an error or exception occurs and debugging is disabled. You can also directly invoke this method yourself by calling Slim::error() directly in your code.

Debugging

Using Slim::config(), you can enable or disable application debugging like this:

//Enable debugging (on by default)
Slim::config('debug', true);

//Disable debugging
Slim::config('debug', false);

If debugging is enabled, a detailed error screen will appear with the error message, the affected file, the file line number, and a stack trace. If debugging is disabled, your custom Error handler will be invoked instead (see above).

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