ILIAS  Release_4_4_x_branch Revision 61816
 All Data Structures Namespaces Files Functions Variables Groups Pages
Slim Class Reference
+ Inheritance diagram for Slim:
+ Collaboration diagram for Slim:

Public Member Functions

 __construct ($userSettings=array())
 Constructor.
 getMode ()
 Get application mode.
 setName ($name)
 Set Slim application name.
 getName ()
 Get Slim application name.
 getLog ()
 Get application Log (lazy-loaded)
 configureMode ($mode, $callable)
 Configure Slim for a given mode.
 config ($name, $value=null)
 Configure Slim Settings.
 map ()
 Add generic route without associated HTTP method.
 get ()
 Add GET route.
 post ()
 Add POST route.
 put ()
 Add PUT route.
 delete ()
 Add DELETE route.
 options ()
 Add OPTIONS route.
 notFound ($callable=null)
 Not Found Handler.
 error ($argument=null)
 Error Handler.
 request ()
 Get the Request object.
 response ()
 Get the Response object.
 router ()
 Get the Router object.
 view ($viewClass=null)
 Get and/or set the View.
 render ($template, $data=array(), $status=null)
 Render a template.
 lastModified ($time)
 Set Last-Modified HTTP Response Header.
 etag ($value, $type= 'strong')
 Set ETag HTTP Response Header.
 setCookie ($name, $value, $time=null, $path=null, $domain=null, $secure=null, $httponly=null)
 Set a normal, unencrypted Cookie.
 getCookie ($name)
 Get the value of a Cookie from the current HTTP Request.
 setEncryptedCookie ($name, $value, $time=null, $path=null, $domain=null, $secure=null, $httponly=null)
 Set an encrypted Cookie.
 getEncryptedCookie ($name)
 Get the value of an encrypted Cookie from the current HTTP request.
 deleteCookie ($name, $path=null, $domain=null, $secure=null, $httponly=null)
 Delete a Cookie (for both normal or encrypted Cookies)
 root ()
 Get the Slim application's absolute directory path.
 stop ()
 Stop.
 halt ($status, $message= '')
 Halt.
 pass ()
 Pass.
 contentType ($type)
 Set the HTTP response Content-Type.
 status ($code)
 Set the HTTP response status code.
 urlFor ($name, $params=array())
 Get the URL for a named Route.
 redirect ($url, $status=302)
 Redirect.
 flash ($key, $value)
 Set flash message for subsequent request.
 flashNow ($key, $value)
 Set flash message for current request.
 flashKeep ()
 Keep flash messages from previous request for subsequent request.
 hook ($name, $callable, $priority=10)
 Assign hook.
 applyHook ($name, $hookArg=null)
 Invoke hook.
 getHooks ($name=null)
 Get hook listeners.
 clearHooks ($name=null)
 Clear hook listeners.
 run ()
 Run the Slim application.

Static Public Member Functions

static autoload ($class)
 Slim auto-loader.
static getInstance ($name= 'default')
 Get Slim application with name.
static handleErrors ($errno, $errstr= '', $errfile= '', $errline= '')
 Handle errors.

Protected Member Functions

 mapRoute ($args)
 Add GET|POST|PUT|DELETE route.
 defaultNotFound ()
 Default Not Found handler.
 defaultError ()
 Default Error handler.

Static Protected Member Functions

static generateErrorMarkup ($message, $file= '', $line= '', $trace= '')
 Generate markup for error message.
static generateTemplateMarkup ($title, $body)
 Generate default template markup.

Protected Attributes

 $name
 $request
 $response
 $router
 $view
 $log
 $settings
 $mode
 $hooks

Static Protected Attributes

static $apps = array()

Detailed Description

Definition at line 71 of file Slim.php.

Constructor & Destructor Documentation

Slim::__construct (   $userSettings = array())

Constructor.

Parameters
array$userSettings
Returns
void

Definition at line 156 of file Slim.php.

References config(), getMode(), request(), response(), router(), setName(), and view().

{
//Merge application settings
$this->settings = array_merge(array(
//Mode
'mode' => 'development',
//Logging
'log.enable' => false,
'log.logger' => null,
'log.path' => './logs',
'log.level' => 4,
//Debugging
'debug' => true,
//View
'templates.path' => './templates',
'view' => 'Slim_View',
//Settings for all cookies
'cookies.lifetime' => '20 minutes',
'cookies.path' => '/',
'cookies.domain' => '',
'cookies.secure' => false,
'cookies.httponly' => false,
//Settings for encrypted cookies
'cookies.secret_key' => 'CHANGE_ME',
'cookies.cipher' => MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode' => MCRYPT_MODE_CBC,
'cookies.encrypt' => true,
'cookies.user_id' => 'DEFAULT',
//Session handler
'session.handler' => new Slim_Session_Handler_Cookies(),
'session.flash_key' => 'flash',
//HTTP
'http.version' => null
), $userSettings);
//Determine application mode
$this->getMode();
//Setup HTTP request and response handling
$this->request = new Slim_Http_Request();
$this->response = new Slim_Http_Response($this->request);
$this->response->setCookieJar(new Slim_Http_CookieJar($this->settings['cookies.secret_key'], array(
'high_confidentiality' => $this->settings['cookies.encrypt'],
'mcrypt_algorithm' => $this->settings['cookies.cipher'],
'mcrypt_mode' => $this->settings['cookies.cipher_mode'],
'enable_ssl' => $this->settings['cookies.secure']
)));
$this->response->httpVersion($this->settings['http.version']);
$this->router = new Slim_Router($this->request);
//Start session if not already started
if ( session_id() === '' ) {
$sessionHandler = $this->config('session.handler');
if ( $sessionHandler instanceof Slim_Session_Handler ) {
$sessionHandler->register($this);
}
session_cache_limiter(false);
session_start();
}
//Setup view with flash messaging
$this->view($this->config('view'))->setData('flash', new Slim_Session_Flash($this->config('session.flash_key')));
//Set app name
if ( !isset(self::$apps['default']) ) {
$this->setName('default');
}
//Set global Error handler after Slim app instantiated
set_error_handler(array('Slim', 'handleErrors'));
}

+ Here is the call graph for this function:

Member Function Documentation

Slim::applyHook (   $name,
  $hookArg = null 
)

Invoke hook.

Parameters
string$nameThe hook name
mixed$hookArgs(Optional) Argument for hooked functions
Returns
mixed

Definition at line 957 of file Slim.php.

References $name.

Referenced by run().

{
if ( !isset($this->hooks[$name]) ) {
$this->hooks[$name] = array(array());
}
if( !empty($this->hooks[$name]) ) {
// Sort by priority, low to high, if there's more than one priority
if ( count($this->hooks[$name]) > 1 ) {
ksort($this->hooks[$name]);
}
foreach( $this->hooks[$name] as $priority ) {
if( !empty($priority) ) {
foreach($priority as $callable) {
$hookArg = call_user_func($callable, $hookArg);
}
}
}
return $hookArg;
}
}

+ Here is the caller graph for this function:

static Slim::autoload (   $class)
static

Slim auto-loader.

This method lazy-loads class files when a given class if first used. Class files must exist in the same directory as this file and be named the same as its class definition (excluding the dot and extension).

Returns
void

Definition at line 139 of file Slim.php.

References $file.

{
if ( strpos($class, 'Slim') !== 0 ) {
return;
}
$file = dirname(__FILE__) . '/' . str_replace('_', DIRECTORY_SEPARATOR, substr($class,5)) . '.php';
if ( file_exists($file) ) {
require $file;
}
}
Slim::clearHooks (   $name = null)

Clear hook listeners.

Clear all listeners for all hooks. If $name is a valid hook name, only the listeners attached to that hook will be cleared.

Parameters
string$nameA hook name (Optional)
Returns
void

Definition at line 1006 of file Slim.php.

References $name.

{
if ( !is_null($name) && isset($this->hooks[(string)$name]) ) {
$this->hooks[(string)$name] = array(array());
} else {
foreach( $this->hooks as $key => $value ) {
$this->hooks[$key] = array(array());
}
}
}
Slim::config (   $name,
  $value = null 
)

Configure Slim Settings.

This method defines application settings and acts as a setter and a getter.

If only one argument is specified and that argument is a string, the value of the setting identified by the first argument will be returned, or NULL if that setting does not exist.

If only one argument is specified and that argument is an associative array, the array will be merged into the existing application settings.

If two arguments are provided, the first argument is the name of the setting to be created or updated, and the second argument is the setting value.

Parameters
string | array$nameIf a string, the name of the setting to set or retrieve. Else an associated array of setting names and values
mixed$valueIf name is a string, the value of the setting identified by $name
Returns
mixed The value of a setting if only one argument is a string

Definition at line 335 of file Slim.php.

References $name.

Referenced by __construct(), deleteCookie(), getLog(), getMode(), run(), setCookie(), setEncryptedCookie(), and view().

{
if ( func_num_args() === 1 ) {
if ( is_array($name) ) {
$this->settings = array_merge($this->settings, $name);
} else {
return in_array($name, array_keys($this->settings)) ? $this->settings[$name] : null;
}
} else {
$this->settings[$name] = $value;
}
}

+ Here is the caller graph for this function:

Slim::configureMode (   $mode,
  $callable 
)

Configure Slim for a given mode.

This method will immediately invoke the callable if the specified mode matches the current application mode. Otherwise, the callable is ignored. This should be called only after you initialize your Slim app.

Parameters
string$mode
mixed$callable
Returns
void

Definition at line 310 of file Slim.php.

References $mode, and getMode().

{
if ( $mode === $this->getMode() && is_callable($callable) ) {
call_user_func($callable);
}
}

+ Here is the call graph for this function:

Slim::contentType (   $type)

Set the HTTP response Content-Type.

Parameters
string$typeThe Content-Type for the Response (ie. text/html)
Returns
void

Definition at line 855 of file Slim.php.

References response().

{
$this->response->header('Content-Type', $type);
}

+ Here is the call graph for this function:

Slim::defaultError ( )
protected

Default Error handler.

Returns
void

Definition at line 1165 of file Slim.php.

References generateTemplateMarkup().

{
echo self::generateTemplateMarkup('Error', '<p>A website error has occured. The website administrator has been notified of the issue. Sorry for the temporary inconvenience.</p>');
}

+ Here is the call graph for this function:

Slim::defaultNotFound ( )
protected

Default Not Found handler.

Returns
void

Definition at line 1157 of file Slim.php.

References generateTemplateMarkup(), and request().

{
echo self::generateTemplateMarkup('404 Page Not Found', '<p>The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.</p><a href="' . $this->request->getRootUri() . '">Visit the Home Page</a>');
}

+ Here is the call graph for this function:

Slim::delete ( )

Add DELETE route.

See Also
Slim::mapRoute
Returns
Slim_Route

Definition at line 434 of file Slim.php.

References mapRoute(), and Slim_Http_Request\METHOD_DELETE.

{
$args = func_get_args();
return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_DELETE);
}

+ Here is the call graph for this function:

Slim::deleteCookie (   $name,
  $path = null,
  $domain = null,
  $secure = null,
  $httponly = null 
)

Delete a Cookie (for both normal or encrypted Cookies)

Remove a Cookie from the client. This method will overwrite an existing Cookie with a new, empty, auto-expiring Cookie. This method's arguments must match the original Cookie's respective arguments for the original Cookie to be removed. If any of this method's arguments are omitted or set to NULL, the default Cookie setting values (set during Slim::init) will be used instead.

Parameters
string$nameThe cookie name
string$pathThe path on the server in which the cookie will be available on
string$domainThe domain that the cookie is available to
bool$secureIndicates that the cookie should only be transmitted over a secure HTTPS connection from the client
bool$httponlyWhen TRUE the cookie will be made accessible only through the HTTP protocol
Returns
void

Definition at line 766 of file Slim.php.

References $name, $path, config(), and response().

{
$path = is_null($path) ? $this->config('cookies.path') : $path;
$domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
$secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
$httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
$this->response->getCookieJar()->deleteCookie( $name, $path, $domain, $secure, $httponly );
}

+ Here is the call graph for this function:

Slim::error (   $argument = null)

Error Handler.

This method defines or invokes the application-wide Error handler. There are two contexts in which this method may be invoked:

  1. When declaring the handler:

If the $argument parameter is callable, this method will register the callable to be invoked when an uncaught Exception is detected, or when otherwise explicitly invoked. The handler WILL NOT be invoked in this context.

  1. When invoking the handler:

If the $argument parameter is not callable, Slim assumes you want to invoke an already-registered handler. If the handler has been registered and is callable, it is invoked and passed the caught Exception as its one and only argument. The error handler's output is captured into an output buffer and sent as the body of a 500 HTTP Response.

Parameters
mixed$argumentCallable|Exception
Returns
void

Definition at line 510 of file Slim.php.

References halt(), and router().

Referenced by run().

{
if ( is_callable($argument) ) {
//Register error handler
$this->router->error($argument);
} else {
//Invoke error handler
ob_start();
$customErrorHandler = $this->router->error();
if ( is_callable($customErrorHandler) ) {
call_user_func_array($customErrorHandler, array($argument));
} else {
call_user_func_array(array($this, 'defaultError'), array($argument));
}
$this->halt(500, ob_get_clean());
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::etag (   $value,
  $type = 'strong' 
)

Set ETag HTTP Response Header.

Set the etag header and stop if the conditional GET request matches. The value argument is a unique identifier for the current resource. The type argument indicates whether the etag should be used as a strong or weak cache validator.

When the current request includes an 'If-None-Match' header with a matching etag, execution is immediately stopped. If the request method is GET or HEAD, a '304 Not Modified' response is sent.

Parameters
string$valueThe etag value
string$typeThe type of etag to create; either "strong" or "weak"
Exceptions
InvalidArgumentExceptionIf provided type is invalid
Returns
void

Definition at line 649 of file Slim.php.

References halt(), request(), and response().

{
//Ensure type is correct
if ( !in_array($type, array('strong', 'weak')) ) {
throw new InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".');
}
//Set etag value
$value = '"' . $value . '"';
if ( $type === 'weak' ) $value = 'W/'.$value;
$this->response->header('ETag', $value);
//Check conditional GET
if ( $etagsHeader = $this->request->headers('IF_NONE_MATCH')) {
$etags = preg_split('@\s*,\s*@', $etagsHeader);
if ( in_array($value, $etags) || in_array('*', $etags) ) $this->halt(304);
}
}

+ Here is the call graph for this function:

Slim::flash (   $key,
  $value 
)

Set flash message for subsequent request.

Parameters
string$key
mixed$value
Returns
void

Definition at line 911 of file Slim.php.

References view().

{
$this->view->getData('flash')->set($key, $value);
}

+ Here is the call graph for this function:

Slim::flashKeep ( )

Keep flash messages from previous request for subsequent request.

Returns
void

Definition at line 929 of file Slim.php.

References view().

{
$this->view->getData('flash')->keep();
}

+ Here is the call graph for this function:

Slim::flashNow (   $key,
  $value 
)

Set flash message for current request.

Parameters
string$key
mixed$value
Returns
void

Definition at line 921 of file Slim.php.

References view().

{
$this->view->getData('flash')->now($key, $value);
}

+ Here is the call graph for this function:

static Slim::generateErrorMarkup (   $message,
  $file = '',
  $line = '',
  $trace = '' 
)
staticprotected

Generate markup for error message.

This method accepts details about an error or exception and generates HTML markup for the 500 response body that will be sent to the client.

Parameters
string$messageThe error message
string$fileThe absolute file path to the affected file
int$lineThe line number in the affected file
string$traceA stack trace of the error
Returns
string

Definition at line 1125 of file Slim.php.

References $file, and generateTemplateMarkup().

{
$body = '<p>The application could not run because of the following error:</p>';
$body .= "<h2>Details:</h2><strong>Message:</strong> $message<br/>";
if ( $file !== '' ) $body .= "<strong>File:</strong> $file<br/>";
if ( $line !== '' ) $body .= "<strong>Line:</strong> $line<br/>";
if ( $trace !== '' ) $body .= '<h2>Stack Trace:</h2>' . nl2br($trace);
return self::generateTemplateMarkup('Slim Application Error', $body);
}

+ Here is the call graph for this function:

static Slim::generateTemplateMarkup (   $title,
  $body 
)
staticprotected

Generate default template markup.

This method accepts a title and body content to generate an HTML page. This is primarily used to generate the layout markup for Error handlers and Not Found handlers.

Parameters
string$titleThe title of the HTML template
string$bodyThe body content of the HTML template
Returns
string

Definition at line 1145 of file Slim.php.

Referenced by defaultError(), defaultNotFound(), and generateErrorMarkup().

{
$html = "<html><head><title>$title</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body>";
$html .= "<h1>$title</h1>";
$html .= $body;
$html .= '</body></html>';
return $html;
}

+ Here is the caller graph for this function:

Slim::get ( )

Add GET route.

See Also
Slim::mapRoute
Returns
Slim_Route

Definition at line 404 of file Slim.php.

References mapRoute(), Slim_Http_Request\METHOD_GET, and Slim_Http_Request\METHOD_HEAD.

{
$args = func_get_args();
}

+ Here is the call graph for this function:

Slim::getCookie (   $name)

Get the value of a Cookie from the current HTTP Request.

Return the value of a cookie from the current HTTP request, or return NULL if cookie does not exist. Cookies created during the current request will not be available until the next request.

Parameters
string$name
Returns
string|null

Definition at line 705 of file Slim.php.

References $name, and request().

{
return $this->request->cookies($name);
}

+ Here is the call graph for this function:

Slim::getEncryptedCookie (   $name)

Get the value of an encrypted Cookie from the current HTTP request.

Return the value of an encrypted cookie from the current HTTP request, or return NULL if cookie does not exist. Encrypted cookies created during the current request will not be available until the next request.

Parameters
string$name
Returns
string|null

Definition at line 744 of file Slim.php.

References $name, and response().

{
$value = $this->response->getCookieJar()->getCookieValue($name);
return ($value === false) ? null : $value;
}

+ Here is the call graph for this function:

Slim::getHooks (   $name = null)

Get hook listeners.

Return an array of registered hooks. If $name is a valid hook name, only the listeners attached to that hook are returned. Else, all listeners are returned as an associative array whose keys are hook names and whose values are arrays of listeners.

Parameters
string$nameA hook name (Optional)
Returns
array|null

Definition at line 988 of file Slim.php.

References $hooks, and $name.

{
if ( !is_null($name) ) {
return isset($this->hooks[(string)$name]) ? $this->hooks[(string)$name] : null;
} else {
return $this->hooks;
}
}
static Slim::getInstance (   $name = 'default')
static

Get Slim application with name.

Parameters
string$nameThe name of the Slim application to fetch
Returns
Slim|null

Definition at line 254 of file Slim.php.

References $name.

Referenced by ilRestFileStorage\createFile(), and ilRestFileStorage\getFile().

{
return isset(self::$apps[(string)$name]) ? self::$apps[(string)$name] : null;
}

+ Here is the caller graph for this function:

Slim::getLog ( )

Get application Log (lazy-loaded)

Returns
Slim_Log

Definition at line 282 of file Slim.php.

References $log, and config().

Referenced by run().

{
if ( !isset($this->log) ) {
$this->log = new Slim_Log();
$this->log->setEnabled($this->config('log.enable'));
$logger = $this->config('log.logger');
if ( $logger ) {
$this->log->setLogger($logger);
} else {
$this->log->setLogger(new Slim_Logger($this->config('log.path'), $this->config('log.level')));
}
}
return $this->log;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::getMode ( )

Get application mode.

Returns
string

Definition at line 231 of file Slim.php.

References $mode, and config().

Referenced by __construct(), and configureMode().

{
if ( !isset($this->mode) ) {
if ( isset($_ENV['SLIM_MODE']) ) {
$this->mode = (string)$_ENV['SLIM_MODE'];
} else {
$envMode = getenv('SLIM_MODE');
if ( $envMode !== false ) {
$this->mode = $envMode;
} else {
$this->mode = (string)$this->config('mode');
}
}
}
return $this->mode;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::getName ( )

Get Slim application name.

Returns
string|null

Definition at line 272 of file Slim.php.

References $name.

{
return $this->name;
}
Slim::halt (   $status,
  $message = '' 
)

Halt.

Halt the application and immediately send an HTTP response with a specific status code and body. This may be used to send any type of response: info, success, redirect, client error, or server error. If you need to render a template AND customize the response status, you should use Slim::render() instead.

Parameters
int$statusThe HTTP response status
string$messageThe HTTP response body
Returns
void

Definition at line 823 of file Slim.php.

References response(), and stop().

Referenced by error(), etag(), lastModified(), notFound(), redirect(), and run().

{
if ( ob_get_level() !== 0 ) {
ob_clean();
}
$this->response->status($status);
$this->response->body($message);
$this->stop();
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static Slim::handleErrors (   $errno,
  $errstr = '',
  $errfile = '',
  $errline = '' 
)
static

Handle errors.

This is the global Error handler that will catch reportable Errors and convert them into ErrorExceptions that are caught and handled by each Slim application.

Parameters
int$errnoThe numeric type of the Error
string$errstrThe error message
string$errfileThe absolute path to the affected file
int$errlineThe line number of the error in the affected file
Returns
true
Exceptions
ErrorException

Definition at line 1105 of file Slim.php.

{
if ( error_reporting() & $errno ) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
return true;
}
Slim::hook (   $name,
  $callable,
  $priority = 10 
)

Assign hook.

Parameters
string$nameThe hook name
mixed$callableA callable object
int$priorityThe hook priority; 0 = high, 10 = low
Returns
void

Definition at line 942 of file Slim.php.

References $name.

{
if ( !isset($this->hooks[$name]) ) {
$this->hooks[$name] = array(array());
}
if ( is_callable($callable) ) {
$this->hooks[$name][(int)$priority][] = $callable;
}
}
Slim::lastModified (   $time)

Set Last-Modified HTTP Response Header.

Set the HTTP 'Last-Modified' header and stop if a conditional GET request's If-Modified-Since header matches the last modified time of the resource. The time argument is a UNIX timestamp integer value. When the current request includes an 'If-Modified-Since' header that matches the specified last modified time, the application will stop and send a '304 Not Modified' response to the client.

Parameters
int$timeThe last modified UNIX timestamp
Exceptions
SlimExceptionReturns HTTP 304 Not Modified response if resource last modified time matches If-Modified-Since header
InvalidArgumentExceptionIf provided timestamp is not an integer
Returns
void

Definition at line 623 of file Slim.php.

References halt(), request(), and response().

{
if ( is_integer($time) ) {
$this->response->header('Last-Modified', date(DATE_RFC1123, $time));
if ( $time === strtotime($this->request->headers('IF_MODIFIED_SINCE')) ) $this->halt(304);
} else {
throw new InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
}
}

+ Here is the call graph for this function:

Slim::map ( )

Add generic route without associated HTTP method.

See Also
Slim::mapRoute
Returns
Slim_Route

Definition at line 394 of file Slim.php.

References mapRoute().

{
$args = func_get_args();
return $this->mapRoute($args);
}

+ Here is the call graph for this function:

Slim::mapRoute (   $args)
protected

Add GET|POST|PUT|DELETE route.

Adds a new route to the router with associated callable. This route will only be invoked when the HTTP request's method matches this route's method.

ARGUMENTS:

First: string The URL pattern (REQUIRED) In-Between: mixed Anything that returns TRUE for is_callable (OPTIONAL) Last: mixed Anything that returns TRUE for is_callable (REQUIRED)

The first argument is required and must always be the route pattern (ie. '/books/:id').

The last argument is required and must always be the callable object to be invoked when the route matches an HTTP request.

You may also provide an unlimited number of in-between arguments; each interior argument must be callable and will be invoked in the order specified before the route's callable is invoked.

USAGE:

Slim::get('/foo'[, middleware, middleware, ...], callable);

Parameters
array(See notes above)
Returns
Slim_Route

Definition at line 379 of file Slim.php.

References router().

Referenced by delete(), get(), map(), options(), post(), and put().

{
$pattern = array_shift($args);
$callable = array_pop($args);
$route = $this->router->map($pattern, $callable);
if ( count($args) > 0 ) {
$route->setMiddleware($args);
}
return $route;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::notFound (   $callable = null)

Not Found Handler.

This method defines or invokes the application-wide Not Found handler. There are two contexts in which this method may be invoked:

  1. When declaring the handler:

If the $callable parameter is not null and is callable, this method will register the callable to be invoked when no routes match the current HTTP request. It WILL NOT invoke the callable.

  1. When invoking the handler:

If the $callable parameter is null, Slim assumes you want to invoke an already-registered handler. If the handler has been registered and is callable, it is invoked and sends a 404 HTTP Response whose body is the output of the Not Found handler.

Parameters
mixed$callableAnything that returns true for is_callable()
Returns
void

Definition at line 471 of file Slim.php.

References halt(), and router().

Referenced by run().

{
if ( !is_null($callable) ) {
$this->router->notFound($callable);
} else {
ob_start();
$customNotFoundHandler = $this->router->notFound();
if ( is_callable($customNotFoundHandler) ) {
call_user_func($customNotFoundHandler);
} else {
call_user_func(array($this, 'defaultNotFound'));
}
$this->halt(404, ob_get_clean());
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::options ( )

Add OPTIONS route.

See Also
Slim::mapRoute
Returns
Slim_Route

Definition at line 444 of file Slim.php.

References mapRoute(), and Slim_Http_Request\METHOD_OPTIONS.

{
$args = func_get_args();
return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_OPTIONS);
}

+ Here is the call graph for this function:

Slim::pass ( )

Pass.

This method will cause the Router::dispatch method to ignore the current route and continue to the next matching route in the dispatch loop. If no subsequent mathing routes are found, a 404 Not Found response will be sent to the client.

Exceptions
Slim_Exception_Pass
Returns
void

Definition at line 843 of file Slim.php.

{
if ( ob_get_level() !== 0 ) {
ob_clean();
}
throw new Slim_Exception_Pass();
}
Slim::post ( )

Add POST route.

See Also
Slim::mapRoute
Returns
Slim_Route

Definition at line 414 of file Slim.php.

References mapRoute(), and Slim_Http_Request\METHOD_POST.

Referenced by ilRestServer\init().

{
$args = func_get_args();
return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_POST);
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::put ( )

Add PUT route.

See Also
Slim::mapRoute
Returns
Slim_Route

Definition at line 424 of file Slim.php.

References mapRoute(), and Slim_Http_Request\METHOD_PUT.

{
$args = func_get_args();
return $this->mapRoute($args)->via(Slim_Http_Request::METHOD_PUT);
}

+ Here is the call graph for this function:

Slim::redirect (   $url,
  $status = 302 
)

Redirect.

This method immediately redirects to a new URL. By default, this issues a 302 Found response; this is considered the default generic redirect response. You may also specify another valid 3xx status code if you want. This method will automatically set the HTTP Location header for you using the URL parameter and place the destination URL into the response body.

Parameters
string$urlThe destination URL
int$statusThe HTTP redirect status code (Optional)
Exceptions
InvalidArgumentExceptionIf status parameter is not a valid 3xx status code
Returns
void

Definition at line 894 of file Slim.php.

References halt(), and response().

Referenced by run().

{
if ( $status >= 300 && $status <= 307 ) {
$this->response->header('Location', (string)$url);
$this->halt($status, (string)$url);
} else {
throw new InvalidArgumentException('Slim::redirect only accepts HTTP 300-307 status codes.');
}
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::render (   $template,
  $data = array(),
  $status = null 
)

Render a template.

Call this method within a GET, POST, PUT, DELETE, NOT FOUND, or ERROR callable to render a template whose output is appended to the current HTTP response body. How the template is rendered is delegated to the current View.

Parameters
string$templateThe name of the template passed into the View::render method
array$dataAssociative array of data made available to the View
int$statusThe HTTP response status code to use (Optional)
Returns
void

Definition at line 598 of file Slim.php.

References response(), and view().

{
if ( !is_null($status) ) {
$this->response->status($status);
}
$this->view->appendData($data);
$this->view->display($template);
}

+ Here is the call graph for this function:

Slim::request ( )

Get the Request object.

Returns
Slim_Http_Request

Definition at line 533 of file Slim.php.

References $request.

Referenced by __construct(), defaultNotFound(), etag(), getCookie(), lastModified(), root(), and run().

{
}

+ Here is the caller graph for this function:

Slim::response ( )

Get the Response object.

Returns
Slim_Http_Response

Definition at line 541 of file Slim.php.

References $response.

Referenced by __construct(), contentType(), deleteCookie(), etag(), getEncryptedCookie(), halt(), lastModified(), redirect(), render(), run(), setCookie(), setEncryptedCookie(), status(), and stop().

{
}

+ Here is the caller graph for this function:

Slim::root ( )

Get the Slim application's absolute directory path.

This method returns the absolute path to the Slim application's directory. If the Slim application is installed in a public-accessible sub-directory, the sub-directory path will be included. This method will always return an absolute path WITH a trailing slash.

Returns
string

Definition at line 786 of file Slim.php.

References request().

{
return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . rtrim($this->request->getRootUri(), '/') . '/';
}

+ Here is the call graph for this function:

Slim::router ( )

Get the Router object.

Returns
Slim_Router

Definition at line 549 of file Slim.php.

References $router.

Referenced by __construct(), error(), mapRoute(), notFound(), run(), and urlFor().

{
return $this->router;
}

+ Here is the caller graph for this function:

Slim::run ( )

Run the Slim application.

This method is the "meat and potatoes" of Slim and should be the last method called. This fires up Slim, invokes the Route that matches the current request, and returns the response to the client.

This method will invoke the Not Found handler if no matching routes are found.

This method will also catch any unexpected Exceptions thrown by this application; the Exceptions will be logged to this application's log and rethrown to the global Exception handler.

Returns
void

Definition at line 1034 of file Slim.php.

References applyHook(), config(), error(), getLog(), halt(), notFound(), redirect(), request(), response(), router(), and view().

{
try {
try {
$this->applyHook('slim.before');
ob_start();
$this->applyHook('slim.before.router');
$dispatched = false;
$httpMethod = $this->request()->getMethod();
$httpMethodsAllowed = array();
foreach ( $this->router as $route ) {
if ( $route->supportsHttpMethod($httpMethod) ) {
try {
$this->applyHook('slim.before.dispatch');
$dispatched = $route->dispatch();
$this->applyHook('slim.after.dispatch');
if ( $dispatched ) {
break;
}
} catch ( Slim_Exception_Pass $e ) {
continue;
}
} else {
$httpMethodsAllowed = array_merge($httpMethodsAllowed, $route->getHttpMethods());
}
}
if ( !$dispatched ) {
if ( $httpMethodsAllowed ) {
$this->response()->header('Allow', implode(' ', $httpMethodsAllowed));
$this->halt(405);
} else {
$this->notFound();
}
}
$this->response()->write(ob_get_clean());
$this->applyHook('slim.after.router');
$this->view->getData('flash')->save();
session_write_close();
$this->response->send();
$this->applyHook('slim.after');
} catch ( Slim_Exception_RequestSlash $e ) {
$this->redirect($this->request->getRootUri() . $this->request->getResourceUri() . '/', 301);
} catch ( Exception $e ) {
if ( $e instanceof Slim_Exception_Stop ) throw $e;
$this->getLog()->error($e);
if ( $this->config('debug') === true ) {
$this->halt(500, self::generateErrorMarkup($e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString()));
} else {
$this->error($e);
}
}
} catch ( Slim_Exception_Stop $e ) {
//Exit application context
}
}

+ Here is the call graph for this function:

Slim::setCookie (   $name,
  $value,
  $time = null,
  $path = null,
  $domain = null,
  $secure = null,
  $httponly = null 
)

Set a normal, unencrypted Cookie.

Parameters
string$nameThe cookie name
mixed$valueThe cookie value
mixed$timeThe duration of the cookie; If integer, should be UNIX timestamp; If string, converted to UNIX timestamp with strtotime;
string$pathThe path on the server in which the cookie will be available on
string$domainThe domain that the cookie is available to
bool$secureIndicates that the cookie should only be transmitted over a secure HTTPS connection to/from the client
bool$httponlyWhen TRUE the cookie will be made accessible only through the HTTP protocol
Returns
void

Definition at line 686 of file Slim.php.

References $name, $path, config(), and response().

{
$time = is_null($time) ? $this->config('cookies.lifetime') : $time;
$path = is_null($path) ? $this->config('cookies.path') : $path;
$domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
$secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
$httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
$this->response->getCookieJar()->setClassicCookie($name, $value, $time, $path, $domain, $secure, $httponly);
}

+ Here is the call graph for this function:

Slim::setEncryptedCookie (   $name,
  $value,
  $time = null,
  $path = null,
  $domain = null,
  $secure = null,
  $httponly = null 
)

Set an encrypted Cookie.

Parameters
string$nameThe cookie name
mixed$valueThe cookie value
mixed$timeThe duration of the cookie; If integer, should be UNIX timestamp; If string, converted to UNIX timestamp with strtotime;
string$pathThe path on the server in which the cookie will be available on
string$domainThe domain that the cookie is available to
bool$secureIndicates that the cookie should only be transmitted over a secure HTTPS connection from the client
bool$httponlyWhen TRUE the cookie will be made accessible only through the HTTP protocol
Returns
void

Definition at line 724 of file Slim.php.

References $name, $path, config(), and response().

{
$time = is_null($time) ? $this->config('cookies.lifetime') : $time;
$path = is_null($path) ? $this->config('cookies.path') : $path;
$domain = is_null($domain) ? $this->config('cookies.domain') : $domain;
$secure = is_null($secure) ? $this->config('cookies.secure') : $secure;
$httponly = is_null($httponly) ? $this->config('cookies.httponly') : $httponly;
$userId = $this->config('cookies.user_id');
$this->response->getCookieJar()->setCookie($name, $value, $userId, $time, $path, $domain, $secure, $httponly);
}

+ Here is the call graph for this function:

Slim::setName (   $name)

Set Slim application name.

Parameters
string$nameThe name of this Slim application
Returns
void

Definition at line 263 of file Slim.php.

References $name.

Referenced by __construct().

{
$this->name = $name;
self::$apps[$name] = $this;
}

+ Here is the caller graph for this function:

Slim::status (   $code)

Set the HTTP response status code.

Parameters
int$statusThe HTTP response status code
Returns
void

Definition at line 864 of file Slim.php.

References response().

{
$this->response->status($code);
}

+ Here is the call graph for this function:

Slim::stop ( )

Stop.

Send the current Response as is and stop executing the Slim application. The thrown exception will be caught by the Slim custom exception handler which exits this script.

Exceptions
Slim_Exception_Stop
Returns
void

Definition at line 800 of file Slim.php.

References response(), and view().

Referenced by halt().

{
$flash = $this->view->getData('flash');
if ( $flash ) {
$flash->save();
}
session_write_close();
$this->response->send();
throw new Slim_Exception_Stop();
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Slim::urlFor (   $name,
  $params = array() 
)

Get the URL for a named Route.

Parameters
string$nameThe route name
array$paramsKey-value array of URL parameters
Exceptions
RuntimeExceptionIf named route does not exist
Returns
string

Definition at line 875 of file Slim.php.

References $name, and router().

{
return $this->router->urlFor($name, $params);
}

+ Here is the call graph for this function:

Slim::view (   $viewClass = null)

Get and/or set the View.

This method declares the View to be used by the Slim application. If the argument is a string, Slim will instantiate a new object of the same class. If the argument is an instance of View or a subclass of View, Slim will use the argument as the View.

If a View already exists and this method is called to create a new View, data already set in the existing View will be transferred to the new View.

Parameters
string | Slim_View$viewClassThe name of a Slim_View class; An instance of Slim_View;
Returns
Slim_View

Definition at line 569 of file Slim.php.

References $view, and config().

Referenced by __construct(), flash(), flashKeep(), flashNow(), render(), run(), and stop().

{
if ( !is_null($viewClass) ) {
$existingData = is_null($this->view) ? array() : $this->view->getData();
if ( $viewClass instanceOf Slim_View ) {
$this->view = $viewClass;
} else {
$this->view = new $viewClass();
}
$this->view->appendData($existingData);
$this->view->setTemplatesDirectory($this->config('templates.path'));
}
return $this->view;
}

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Field Documentation

Slim::$apps = array()
staticprotected

Definition at line 76 of file Slim.php.

Slim::$hooks
protected
Initial value:
array(
'slim.before' => array(array()),
'slim.before.router' => array(array()),
'slim.before.dispatch' => array(array()),
'slim.after.dispatch' => array(array()),
'slim.after.router' => array(array()),
'slim.after' => array(array())
)

Definition at line 121 of file Slim.php.

Referenced by getHooks().

Slim::$log
protected

Definition at line 106 of file Slim.php.

Referenced by getLog().

Slim::$mode
protected

Definition at line 116 of file Slim.php.

Referenced by configureMode(), and getMode().

Slim::$request
protected

Definition at line 86 of file Slim.php.

Referenced by request().

Slim::$response
protected

Definition at line 91 of file Slim.php.

Referenced by response().

Slim::$router
protected

Definition at line 96 of file Slim.php.

Referenced by router().

Slim::$settings
protected

Definition at line 111 of file Slim.php.

Slim::$view
protected

Definition at line 101 of file Slim.php.

Referenced by view().


The documentation for this class was generated from the following file: