Slim Framework Documentation
Slim Framework Documentation
Slim Framework Documentation
com)
GETTINGSTARTED
CONFIGURATION
ROUTING
ENVIRONMENT
REQUEST
RESPONSE
VIEW
HTTPCACHING
MIDDLEWARE
HOOKS
FLASHMESSAGES
SESSIONS
LOGGING
ERRORHANDLING
GettingStarted
tp://docs.slimframework.com/#Getting
arted)
Installation
ComposerInstall
Installcomposerinyourproject:
curlshttps://getcomposer.org/installer|php
Createa composer.jsonfileinyourprojectroot:
{
"require":{
"slim/slim":"2.*"
}
}
Installviacomposer:
phpcomposer.pharinstall
Addthislinetoyourapplications index.phpfile:
<?php
require'vendor/autoload.php'
ManualInstall
DownloadandextracttheSlimFramworkintoyourprojectdirectoryand requireitinyourapplications
index.phpfile.YoullalsoneedtoregisterSlimsautoloader.
<?php
require'Slim/Slim.php'
\Slim\Slim::registerAutoloader()
BacktoTop
SystemRequirements
PHP>=5.3.0
The mcryptextensionisrequiredonlyifyouuseencryptedcookies.
BacktoTop
HelloWorld
InstantiateaSlimapplication:
$app=new\Slim\Slim()
DefineaHTTPGETroute:
$app>get('/hello/:name',function($name){
echo"Hello,$name"
})
RuntheSlimapplication:
$app>run()
BacktoTop
Configuration
cs.slimframework.com/#Configuration)
ConfigurationOverview
TherearetwowaystoapplysettingstotheSlimapplication.FirstduringSlimapplicationinstantiationand
secondafterinstantiation.AllsettingscanbeappliedatinstatiationtimebypassingSlimsconstructoran
associativearray.Allsettingscanberetrievedandmodifiedafterinstantiation,howeversomeofthemcan
notbedonesimplybyusingtheconfigapplicationinstancemethodbutwillbedemonstratedasnecessary
below.BeforeIlisttheavailablesettings,Iwanttoquicklyexplainhowyoumaydefineandinspect
settingswithyourSlimapplication.
DuringInstantiation
Todefinesettingsuponinstantiation,passanassociativearrayintotheSlimconstructor.
<?php
$app=newSlim(array(
'debug'=>true
))
AfterInstantiation
Todefinesettingsafterinstantiation,themajoritycanusetheconfigapplicationinstancemethodthefirst
argumentisthesettingnameandthesecondargumentisthesettingvalue.
<?php
$app>config('debug',false)
Youmayalsodefinemultiplesettingsatonceusinganassociativearray:
<?php
$app>config(array(
'debug'=>true,
'templates.path'=>'../templates'
))
Toretrievethevalueofasetting,youalsousetheconfigapplicationinstancemethodhowever,youonly
passoneargumentthenameofthesettingyouwishtoinspect.Ifthesettingyourequestdoesnotexist,
nullisreturned.
<?php
$settingValue=$app>config('templates.path')//returns"../templates"
Youarenotlimitedtothesettingsshownbelowyoumayalsodefineyourown.
BacktoTop
ApplicationSettings
mode
Thisisanidentifierfortheapplicationscurrentmodeofoperation.ThemodedoesnotaffectaSlim
applicationsinternalfunctionality.Instead,themodeisonlyforyoutooptionallyinvokeyourowncodefor
agivenmodewiththe configMode()applicationmethod.
Theapplicationmodeisdeclaredduringinstantiation,eitherasanenvironmentvariableorasan
argumenttotheSlimapplicationconstructor.Itcannotbechangedafterward.Themodemaybeanything
youwantdevelopment,test,andproductionaretypical,butyouarefreetouseanythingyouwant
(e.g.foo).
<?php
$app=new\Slim\Slim(array(
'mode'=>'development'
))
DataType
string
DefaultValue
development
debug
HeadsUp!Slimconvertserrorsinto`ErrorException`instances.
Ifdebuggingisenabled,Slimwilluseitsbuiltinerrorhandlertodisplaydiagnosticinformationfor
uncaughtExceptions.Ifdebuggingisdisabled,Slimwillinsteadinvokeyourcustomerrorhandler,passing
ittheotherwiseuncaughtExceptionasitsfirstandonlyargument.
<?php
$app=new\Slim\Slim(array(
'debug'=>true
))
DataType
boolean
DefaultValue
true
log.writer
Useacustomlogwritertodirectloggedmessagestotheappropriateoutputdestination.Bydefault,Slims
loggerwillwriteloggedmessagesto STDERR.Ifyouuseacustomlogwriter,itmustimplementthis
interface:
publicwrite(mixed$message,int$level)
The write()methodisresponsibleforsendingtheloggedmessage(notnecessarilyastring)tothe
appropriateoutputdestination(e.g.atextfile,adatabase,oraremotewebservice).
TospecifyacustomlogwriterafterinstantiationyoumustaccessSlimsloggerdirectlyanduseits
setWriter()method:
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'log.writer'=>new\My\LogWriter()
))
//Afterinstantiation
$log=$app>getLog()
$log>setWriter(new\My\LogWriter())
DataType
mixed
DefaultValue
\Slim\LogWriter
log.level
HeadsUp!Usetheconstantsdefinedin`\Slim\Log`insteadofintegers.
Slimhasfive(5)logmessagelevels:
\Slim\Log::DEBUG
\Slim\Log::INFO
\Slim\Log::WARN
\Slim\Log::ERROR
\Slim\Log::FATAL
The log.levelapplicationsettingdetermineswhichloggedmessageswillbehonoredandwhichwillbe
ignored.Forexample,ifthe log.levelsettingis \Slim\Log::INFO,debugmessageswillbeignored
whileinfo,warn,error,andfatalmessageswillbelogged.
TochangethissettingafterinstantiationyoumustaccessSlimsloggerdirectlyanduseits setLevel()
method.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'log.level'=>\Slim\Log::DEBUG
))
//Afterinstantiation
$log=$app>getLog()
$log>setLevel(\Slim\Log::WARN)
DataType
integer
DefaultValue
\Slim\Log::DEBUG
log.enabled
ThisenablesordisablesSlimslogger.TochangethissettingafterinstantiationyouneedtoaccessSlims
loggerdirectlyanduseits setEnabled()method.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'log.enabled'=>true
))
//Afterinstantiation
$log=$app>getLog()
$log>setEnabled(true)
DataType
boolean
DefaultValue
true
templates.path
TherelativeorabsolutepathtothefilesystemdirectorythatcontainsyourSlimapplicationstemplatefiles.
ThispathisreferencedbytheSlimapplicationsViewtofetchandrendertemplates.
TochangethissettingafterinstantiationyouneedtoaccessSlimsviewdirectlyanduseits
setTemplatesDirectory()method.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'templates.path'=>'./templates'
))
//Afterinstantiation
$view=$app>view()
$view>setTemplatesDirectory('./templates')
DataType
string
DefaultValue
./templates
view
TheViewclassorinstanceusedbytheSlimapplication.Tochangethissettingafterinstantiationyou
needtousetheSlimapplications view()method.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'view'=>new\My\View()
))
//Afterinstantiation
$app>view(new\My\View())
DataType
string|\Slim\View
DefaultValue
\Slim\View
cookies.lifetime
DeterminesthelifetimeofHTTPcookiescreatedbytheSlimapplication.Ifthisisaninteger,itmustbea
validUNIXtimestampatwhichthecookieexpires.Ifthisisastring,itisparsedbythe strtotime()
functiontoextrapolateavalidUNIXtimestampatwhichthecookieexpires.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.lifetime'=>'20minutes'
))
//Afterinstantiation
$app>config('cookies.lifetime','20minutes')
DataType
integer|string
DefaultValue
20minutes
cookies.path
DeterminesthedefaultHTTPcookiepathifnoneisspecifiedwheninvokingtheSlimapplications
setCookie()or setEncryptedCookie()methods.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.path'=>'/'
))
//Afterinstantiation
$app>config('cookies.lifetime','/')
DataType
string
DefaultValue
/
cookies.domain
DeterminesthedefaultHTTPcookiedomainifnonespecifiedwheninvokingtheSlimapplications
setCookie()or setEncryptedCookie()methods.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.domain'=>'domain.com'
))
//Afterinstantiation
$app>config('cookies.domain','domain.com')
DataType
string
DefaultValue
null
cookies.secure
DetermineswhetherornotcookiesaredeliveredonlyviaHTTPS.Youmayoverridethissettingwhen
invokingtheSlimapplications setCookie()or setEncryptedCookie()methods.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.secure'=>false
))
//Afterinstantiation
$app>config('cookies.secure',false)
DataType
boolean
DefaultValue
false
cookies.httponly
DetermineswhetherornotcookiesaredeliveredonlyviatheHTTPprotocol.Youmayoverridethis
settingwheninvokingtheSlimapplications setCookie()or setEncryptedCookie()methods.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.httponly'=>false
))
//Afterinstantiation
$app>config('cookies.httponly',false)
DataType
boolean
DefaultValue
false
cookies.secret_key
Thesecretkeyusedforcookieencryption.YoushouldchangethissettingifyouuseencryptedHTTP
cookiesinyourSlimapplication.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.secret_key'=>'secret'
))
//Afterinstantiation
$app>config('cookies.secret_key','secret')
DataType
string
DefaultValue
CHANGE_ME
cookies.cipher
ThemcryptcipherusedforHTTPcookieencryption.Seeavailableciphers
(http://php.net/manual/en/mcrypt.ciphers.php).
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.cipher'=>MCRYPT_RIJNDAEL_256
))
//Afterinstantiation
$app>config('cookies.cipher',MCRYPT_RIJNDAEL_256)
DataType
integer
DefaultValue
MCRYPT_RIJNDAEL_256
cookies.cipher_mode
ThemcryptciphermodeusedforHTTPcookieencryption.Seeavailableciphermodes
(http://php.net/manual/en/mcrypt.ciphers.php).
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'cookies.cipher_mode'=>MCRYPT_MODE_CBC
))
//Afterinstantiation
$app>config('cookies.cipher_mode',MCRYPT_MODE_CBC)
DataType
integer
DefaultValue
MCRYPT_MODE_CBC
http.version
Bydefault,SlimreturnsanHTTP/1.1responsetotheclient.Usethissettingifyouneedtoreturnan
HTTP/1.0response.ThisisusefulifyouusePHPFogorannginxserverconfigurationwhereyou
communicatewithbackendproxiesratherthandirectlywiththeHTTPclient.
<?php
//Duringinstantiation
$app=new\Slim\Slim(array(
'http.version'=>'1.1'
))
//Afterinstantiation
$app>config('http.version','1.1')
DataType
string
DefaultValue
1.1
BacktoTop
ApplicationNamesandScopes
WhenyoubuildaSlimapplicationyouwillentervariousscopesinyourcode(e.g.globalscopeand
functionscope).YouwilllikelyneedareferencetoyourSlimapplicationineachscope.Thereareseveral
waystodothis:
UseapplicationnameswiththeSlimapplications getInstance()staticmethod
Curryanapplicationinstanceintofunctionscopewiththe usekeyword
ApplicationNames
EverySlimapplicationmaybegivenaname.Thisisoptional.NameshelpyougetareferencetoaSlim
applicationinstanceinanyscopethroughoutyourcode.Hereishowyousetandgetanapplications
name:
<?php
$app=new\Slim\Slim()
$app>setName('foo')
$name=$app>getName()//"foo"
ScopeResolution
SohowdoyougetareferencetoyourSlimapplication?Theexamplebelowdemonstrateshowtoobtain
areferencetoaSlimapplicationwithinaroutecallbackfunction.The $appvariableisusedintheglobal
scopetodefinetheHTTPGETroute.Butthe $appvariableisalsoneededwithintheroutescallback
scopetorenderatemplate.
<?php
$app=new\Slim\Slim()
$app>get('/foo',function(){
$app>render('foo.php')//<ERROR
})
Thisexamplefailsbecausethe $appvariableisunavailableinsidetheroutecallbackfunction.
Currying
Wecaninjectthe $appvariableintothecallbackfunctionwiththe usekeyword:
<?php
$app=new\Slim\Slim()
$app>get('/foo',function()use($app){
$app>render('foo.php')//<SUCCESS
})
FetchbyName
YoucanusetheSlimapplications getInstance()staticmethod,too:
<?php
$app=new\Slim\Slim()
$app>get('/foo','foo')
functionfoo(){
$app=Slim::getInstance()
$app>render('foo.php')
}
BacktoTop
ApplicationModes
Itiscommonpracticetorunwebapplicationsinaspecificmodedependingonthecurrentstateofthe
project.Ifyouaredevelopingtheapplication,youwillruntheapplicationindevelopmentmodeifyou
aretestingtheapplication,youwillruntheapplicationintestmodeifyoulaunchtheapplication,youwill
runtheapplicationinproductionmode.
SlimsupportstheconceptofmodesinthatyoumaydefineyourownmodesandpromptSlimtoprepare
itselfappropriatelyforthecurrentmode.Forexample,youmaywanttoenabledebuggingin
developmentmodebutnotinproductionmode.Theexamplesbelowdemonstratehowtoconfigure
Slimdifferentlyforagivenmode.
Whatisamode?
Technically,anapplicationmodeismerelyastringoftextlikedevelopmentorproductionthathas
anassociatedcallbackfunctionusedtopreparetheSlimapplicationappropriately.Theapplicationmode
maybeanythingyoulike:testing,production,development,orevenfoo.
HowdoIsettheapplicationmode?
HeadsUp!Theapplicationmodemayonlybesetduringapplicationinstantiation.Itmaynotbe
changedafterward.
Useanenvironmentvariable
IfSlimseesanenvironmentvariablenamedSLIM_MODE,itwillsettheapplicationmodetothat
variablesvalue.
<?php
$_ENV['SLIM_MODE']='production'
Useapplicationsetting
Ifanenvironmentvariableisnotfound,Slimwillnextlookforthemodeintheapplicationsettings.
<?php
$app=new\Slim\Slim(array(
'mode'=>'production'
))
Defaultmode
Iftheenvironmentvariableandapplicationsettingarenotfound,Slimwillsettheapplicationmodeto
development.
ConfigureforaSpecificMode
AfteryouinstantiateaSlimapplication,youmayconfiguretheSlimapplicationforaspecificmodewiththe
Slimapplications configureMode()method.Thismethodacceptstwoarguments:thenameofthetarget
modeandacallablefunctiontobeimmediatelyinvokedifthefirstargumentmatchesthecurrent
applicationmode.
Assumethecurrentapplicationmodeisproduction.Onlythecallableassociatedwiththeproduction
modewillbeinvoked.Thecallableassociatedwiththedevelopmentmodewillbeignoreduntilthe
applicationmodeischangedtodevelopment.
<?php
//Setthecurrentmode
$app=new\Slim\Slim(array(
'mode'=>'production'
))
//Onlyinvokedifmodeis"production"
$app>configureMode('production',function()use($app){
$app>config(array(
'log.enable'=>true,
'debug'=>false
))
})
//Onlyinvokedifmodeis"development"
$app>configureMode('development',function()use($app){
$app>config(array(
'log.enable'=>false,
'debug'=>true
))
})
BacktoTop
Routing
p://docs.slimframework.com/#Routing)
RoutingOverview
TheSlimFrameworkhelpsyoumapresourceURIstocallbackfunctionsforspecificHTTPrequest
methods(e.g.GET,POST,PUT,DELETE,OPTIONSorHEAD).ASlimapplicationwillinvokethefirst
routethatmatchesthecurrentHTTPrequestsURIandmethod.
IftheSlimapplicationdoesnotfindrouteswithURIsthatmatchtheHTTPrequestURIandmethod,itwill
automaticallyreturna404NotFoundresponse.
BacktoTop
GETRoutes
UsetheSlimapplications get()methodtomapacallbackfunctiontoaresourceURIthatisrequested
withtheHTTPGETmethod.
<?php
$app=new\Slim\Slim()
$app>get('/books/:id',function($id){
//Showbookidentifiedby$id
})
Inthisexample,anHTTPGETrequestfor/books/1willinvoketheassociatedcallbackfunction,passing
1asthecallbacksargument.
ThefirstargumentoftheSlimapplications get()methodistheresourceURI.Thelastargumentis
anythingthatreturns truefor is_callable().Typically,thelastargumentwillbeananonymous
function(http://php.net/manual/en/functions.anonymous.php).
BacktoTop
POSTRoutes
UsetheSlimapplications post()methodtomapacallbackfunctiontoaresourceURIthatisrequested
withtheHTTPPOSTmethod.
<?php
$app=new\Slim\Slim()
$app>post('/books',function(){
//Createbook
})
Inthisexample,anHTTPPOSTrequestfor/bookswillinvoketheassociatedcallbackfunction
ThefirstargumentoftheSlimapplications post()methodistheresourceURI.Thelastargumentis
anythingthatreturns truefor is_callable().Typically,thelastargumentwillbeananonymous
function(http://php.net/manual/en/functions.anonymous.php).
BacktoTop
PUTRoutes
UsetheSlimapplications put()methodtomapacallbackfunctiontoaresourceURIthatisrequested
withtheHTTPPUTmethod.
<?php
$app=new\Slim\Slim()
$app>put('/books/:id',function($id){
//Updatebookidentifiedby$id
})
Inthisexample,anHTTPPUTrequestfor/books/1willinvoketheassociatedcallbackfunction,passing
1asthecallbackfunctionsargument.
ThefirstargumentoftheSlimapplications put()methodistheresourceURI.Thelastargumentis
anythingthatreturns truefor is_callable().Typically,thelastargumentwillbeananonymous
function(http://php.net/manual/en/functions.anonymous.php).
MethodOverride
Unfortunately,modernbrowsersdonotprovidenativesupportforHTTPPUTrequests.Toworkaround
thislimitation,ensureyourHTMLformsmethodattributeispost,thenaddamethodoverrideparameter
toyourHTMLformlikethis:
<formaction="/books/1"method="post">
...otherformfieldshere...
<inputtype="hidden"name="_METHOD"value="PUT"/>
<inputtype="submit"value="UpdateBook"/>
</form>
IfyouareusingBackbone.js(http://documentcloud.github.com/backbone/)oracommandlineHTTP
client,youmayalsooverridetheHTTPmethodbyusingtheXHTTPMethodOverrideheader.
BacktoTop
DELETERoutes
UsetheSlimapplications delete()methodtomapacallbackfunctiontoaresourceURIthatis
requestedwiththeHTTPDELETEmethod.
<?php
$app=new\Slim\Slim()
$app>delete('/books/:id',function($id){
//Deletebookidentifiedby$id
})
Inthisexample,anHTTPDELETErequestfor/books/1willinvoketheassociatedcallbackfunction,
passing1asthecallbackfunctionsargument.
ThefirstargumentoftheSlimapplications delete()methodistheresourceURI.Thelastargumentis
anythingthatreturns truefor is_callable().Typically,thelastargumentwillbeananonymous
function(http://php.net/manual/en/functions.anonymous.php).
MethodOverride
Unfortunately,modernbrowsersdonotprovidenativesupportforHTTPDELETErequests.Towork
aroundthislimitation,ensureyourHTMLformsmethodattributeispost,thenaddamethodoverride
parametertoyourHTMLformlikethis:
<formaction="/books/1"method="post">
...otherformfieldshere...
<inputtype="hidden"name="_METHOD"value="DELETE"/>
<inputtype="submit"value="DeleteBook"/>
</form>
IfyouareusingBackbone.js(http://documentcloud.github.com/backbone/)oracommandlineHTTP
client,youmayalsooverridetheHTTPmethodbyusingtheXHTTPMethodOverrideheader.
BacktoTop
OPTIONSRoutes
UsetheSlimapplications options()methodtomapacallbackfunctiontoaresourceURIthatis
requestedwiththeHTTPOPTIONSmethod.
<?php
$app=new\Slim\Slim()
$app>options('/books/:id',function($id){
//Returnresponseheaders
})
Inthisexample,anHTTPOPTIONSrequestfor/books/1willinvoketheassociatedcallbackfunction,
passing1asthecallbackfunctionsargument.
ThefirstargumentoftheSlimapplications options()methodistheresourceURI.Thelastargumentis
anythingthatreturns truefor is_callable().Typically,thelastargumentwillbeananonymous
function(http://php.net/manual/en/functions.anonymous.php).
MethodOverride
Unfortunately,modernbrowsersdonotprovidenativesupportforHTTPOPTIONSrequests.Towork
aroundthislimitation,ensureyourHTMLformsmethodattributeispost,thenaddamethodoverride
parametertoyourHTMLformlikethis:
<formaction="/books/1"method="post">
...otherformfieldshere...
<inputtype="hidden"name="_METHOD"value="OPTIONS"/>
<inputtype="submit"value="FetchOptionsForBook"/>
</form>
IfyouareusingBackbone.js(http://documentcloud.github.com/backbone/)oracommandlineHTTP
client,youmayalsooverridetheHTTPmethodbyusingtheXHTTPMethodOverrideheader.
BacktoTop
CustomHTTPMethods
Oneroute,multipleHTTPmethods
SometimesyoumayneedaroutetorespondtomultipleHTTPmethodssometimesyoumayneeda
routetorespondtoacustomHTTPmethod.YoucanaccomplishbothwiththeRouteobjects via()
method.ThisexampledemonstrateshowtomaparesourceURItoacallbackthatrespondstomultiple
HTTPmethods.
<?php
$app=new\Slim\Slim()
$app>map('/foo/bar',function(){
echo"IrespondtomultipleHTTPmethods!"
})>via('GET','POST')
$app>run()
TheroutedefinedinthisexamplewillrespondtobothGETandPOSTrequestsfortheresourceidentified
by/foo/bar.SpecifyeachappropriateHTTPmethodasaseparatestringargumenttotheRouteobjects
via()method.LikeotherRoutemethods(e.g. name()and conditions()),the via()methodis
chainable:
<?php
$app=new\Slim\Slim()
$app>map('/foo/bar',function(){
echo"Fancy,huh?"
})>via('GET','POST')>name('foo')
$app>run()
Oneroute,customhttpmethods
TheRouteobjects via()methodisnotlimitedtojustGET,POST,PUT,DELETE,andOPTIONS
methods.YoumayalsospecifyyourowncustomHTTPmethods(e.g.ifyouwererespondingtoWebDAV
HTTPrequests).YoucandefinearoutethatrespondstoacustomFOOHTTPmethodlikethis:
<?php
$app=new\Slim\Slim()
$app>map('/hello',function(){
echo"Hello"
})>via('FOO')
$app>run()
BacktoTop
RouteParameters
YoucanembedparametersintorouteresourceURIs.Inthisexample,Ihavetwoparametersinmyroute
URI,:oneand:two.
<?php
$app=new\Slim\Slim()
$app>get('/books/:one/:two',function($one,$two){
echo"Thefirstparamteris".$one
echo"Thesecondparameteris".$two
})
TocreateaURLparameter,prepend:totheparameternameintherouteURIpattern.Whentheroute
matchesthecurrentHTTPrequest,thevaluesforeachrouteparameterareextractedfromtheHTTP
requestURIandarepassedintotheassociatedcallbackfunctioninorderofappearance.
Wildcardrouteparameters
Youmayalsousewildcardrouteparameters.ThesewillcaptureoneormanyURIsegmentsthat
correspondtotheroutepatternswildcardparameterintoanarray.Awildcardparameterisidentifiedbya
+suffixitotherwiseactsthesameasnormalrouteparametersshownabove.Heresanexample:
<?php
$app=new\Slim\Slim()
$app>get('/hello/:name+',function($name){
//Dosomething
})
WhenyouinvokethisexampleapplicationwitharesourceURI/hello/Josh/T/Lockhart,theroute
callbacks $nameargumentwillbeequalto array('Josh','T',Lockhart').
Optionalrouteparameters
HeadsUp!Optionalroutesegmentsareexperimental.Theyshouldonlybeusedinthemanor
demonstratedbelow.
Youmayalsohaveoptionalrouteparameters.Theseareidealforusingonerouteforablogarchive.To
declareoptionalrouteparameters,specifyyourroutepatternlikethis:
<?php
$app=newSlim()
$app>get('/archive(/:year(/:month(/:day)))',function($year=2010,$month=12,$day=05
){
echosprintf('%s%s%s',$year,$month,$day)
})
Eachsubsequentroutesegmentisoptional.ThisroutewillacceptHTTPrequestsfor:
/archive
/archive/2010
/archive/2010/12
/archive/2010/12/05
IfanoptionalroutesegmentisomittedfromtheHTTPrequest,thedefaultvaluesinthecallbacksignature
areusedinstead.
Currently,youcanonlyuseoptionalroutesegmentsinsituationsliketheexampleabovewhereeach
routesegmentissubsequentlyoptional.Youmayfindthisfeatureunstablewhenusedinscenarios
differentfromtheexampleabove.
BacktoTop
RouteNames
Slimletsyouassignanametoaroute.NamingarouteenablesyoutodynamicallygenerateURLsusing
theurlForhelpermethod.WhenyouusetheSlimapplications urlFor()methodtocreateapplication
URLs,youcanfreelychangeroutepatternswithoutbreakingyourapplication.Hereisanexampleofa
namedroute:
<?php
$app=new\Slim\Slim()
$app>get('/hello/:name',function($name){
echo"Hello,$name!"
})>name('hello')
YoumaynowgenerateURLsforthisrouteusingthe urlFor()method,describedlaterinthis
documentation.Theroute name()methodisalsochainable:
<?php
$app=new\Slim\Slim()
$app>get('/hello/:name',function($name){
echo"Hello,$name!"
})>name('hello')>conditions(array('name'=>'\w+'))
BacktoTop
RouteConditions
Slimletsyouassignconditionstorouteparameters.Ifthespecifiedconditionsarenotmet,therouteisnot
run.Forexample,ifyouneedaroutewithasecondsegmentthatmustbeavalid4digityear,youcould
enforcethisconditionlikethis:
<?php
$app=new\Slim\Slim()
$app>get('/archive/:year',function($year){
echo"Youareviewingarchivesfrom$year"
})>conditions(array('year'=>'(19|20)\d\d'))
InvoketheRouteobjects conditions()method.Thefirstandonlyargumentisanassociativearraywith
keysthatmatchanyoftheroutesparametersandvaluesthatareregularexpressions.
Applicationwiderouteconditions
IfmanyofyourSlimapplicationRoutesacceptthesameparametersandusethesameconditions,you
candefinedefaultapplicationwideRouteconditionslikethis:
<?php
\Slim\Route::setDefaultConditions(array(
'firstName'=>'[azAZ]{3,}'
))
Defineapplicationwiderouteconditionsbeforeyoudefineapplicationroutes.Whenyoudefinearoute,
theroutewillautomaticallybeassignedanyapplicationwideRouteconditionsdefinedwith
\Slim\Route::setDefaultConditions().Ifforwhateverreasonyouneedtogettheapplicationwide
defaultrouteconditions,youcanfetchthemwith \Slim\Route::getDefaultConditions().Thisstatic
methodreturnsanarrayexactlyasthedefaultrouteconditionsweredefined.
Youmayoverrideadefaultrouteconditionbyredefiningtheroutesconditionwhenyoudefinetheroute,
likethis:
<?php
$app=new\Slim\Slim()
$app>get('/hello/:firstName',$callable)
>conditions(array('firstName'=>'[az]{10,}'))
Youmayappendnewconditionstoagivenroutelikethis:
<?php
$app=new\Slim\Slim()
$app>get('/hello/:firstName/:lastName',$callable)
>conditions(array('lastName'=>'[az]{10,}'))
BacktoTop
RouteMiddleware
Slimenablesyoutoassociatemiddlewarewithaspecificapplicationroute.Whenthegivenroutematches
thecurrentHTTPrequestandisinvoked,Slimwillfirstinvoketheassociatedmiddlewareintheorderthey
aredefined.
Whatisroutemiddleware?
Routemiddlewareisanythingthatreturns truefor is_callable.Routemiddlewarewillbeinvokedin
thesequencedefinedbeforeitsrelatedroutecallbackisinvoked.
HowdoIaddroutemiddleware?
WhenyoudefineanewapplicationroutewiththeSlimapplications get(), post(), put(),or
delete()methodsyoumustdefinearoutepatternandacallabletobeinvokedwhentheroutematches
anHTTPrequest.
<?php
$app=new\Slim\Slim()
$app>get('/foo',function(){
//Dosomething
})
Intheexampleabove,thefirstargumentistheroutepattern.Thelastargumentisthecallabletobe
invokedwhentheroutematchesthecurrentHTTPrequest.Theroutepatternmustalwaysbethefirst
argument.Theroutecallablemustalwaysbethelastargument.
Youcanassignmiddlewaretothisroutebypassingeachmiddlewareasaseparateinterioror(ahem)
middleargumentlikethis:
<?php
functionmw1(){
echo"Thisismiddleware!"
}
functionmw2(){
echo"Thisismiddleware!"
}
$app=new\Slim\Slim()
$app>get('/foo','mw1','mw2',function(){
//Dosomething
})
Supposeyouwantedtoauthenticatethecurrentuseragainstagivenroleforaspecificroute.Youcould
usesomeclosuremagiclikethis:
<?php
$authenticateForRole=function($role='member'){
returnfunction()use($role){
$user=User::fetchFromDatabaseSomehow()
if($user>belongsToRole($role)===false){
$app=\Slim\Slim::getInstance()
$app>flash('error','Loginrequired')
$app>redirect('/login')
}
}
}
$app=new\Slim\Slim()
$app>get('/foo',$authenticateForRole('admin'),function(){
//Displayadmincontrolpanel
})
Whatargumentsarepassedintoeachroutemiddleware
callable?
Eachmiddlewarecallableisinvokedwithoneargument,thecurrentlymatched \Slim\Routeobject.
<?php
$aBitOfInfo=function(\Slim\Route$route){
echo"Currentrouteis".$route>getName()
}
$app>get('/foo',$aBitOfInfo,function(){
echo"foo"
})
BacktoTop
RouteHelpers
Slimprovidesseveralhelpermethods(exposedviatheSlimapplicationinstance)thatwillhelpyoucontrol
theflowofyourapplication.
<?php
$app>get('/',function()use($app,$obj){
try{
$obj>thisMightThrowException()
$app>redirect('/success')
}catch(\Exception$e){
$app>flash('error',$e>getMessage())
$app>redirect('/error')
}
})
If $obj>thisMightThrowException()doesthrowanExceptionthecodewillrunasexpected.However,if
noexceptionisthrownthecallto$app>redirect()willthrowa \Slim\Exception\StopExceptionthatwill
becaughtbytheuser catchblockratherthanbytheframeworkredirectingthebrowsertothe/error
page.WherepossibleinyourownapplicationyoushouldusetypedExceptionssoyour catchblocksare
moretargetedratherthanswallowingallExceptions.Insomesituationsthe thisMightThrowException()
mightbeanexternalcomponentcallthatyoudontcontrol,inwhichcasetypingallexceptionsthrownmay
notbefeasible.Fortheseinstanceswecanadjustourcodeslightlybymovingthesuccess
$app>redirect()afterthetry/catchblocktofixtheissues.Sinceprocessingwillstopontheerror
redirectthiscodewillnowexecuteasexpected.
<?php
$app>get('/',function()use($app,$obj){
try{
$obj>thisMightThrowException()
}catch(Exception$e){
$app>flash('error',$e>getMessage())
$app>redirect('/error')
}
$app>redirect('/success')
})
Halt
TheSlimapplications halt()methodwillimmediatelyreturnanHTTPresponsewithagivenstatuscode
andbody.Thismethodacceptstwoarguments:theHTTPstatuscodeandanoptionalmessage.Slimwill
immediatelyhaltthecurrentapplicationandsendanHTTPresponsetotheclientwiththespecifiedstatus
andoptionalmessage(astheresponsebody).Thiswilloverridetheexisting \Slim\Http\Response
object.
<?php
$app=new\Slim\Slim()
//Sendadefault500errorresponse
$app>halt(500)
//OrifyouencounteraBalrog...
$app>halt(403,'Youshallnotpass!')
Ifyouwouldliketorenderatemplatewithalistoferrormessages,youshouldusetheSlimapplications
render()methodinstead.
<?php
$app=new\Slim\Slim()
$app>get('/foo',function()use($app){
$errorData=array('error'=>'PermissionDenied')
$app>render('errorTemplate.php',$errorData,403)
})
$app>run()
The halt()methodmaysendanytypeofHTTPresponsetotheclient:informational,success,redirect,
notfound,clienterror,orservererror.
Pass
AroutecantelltheSlimapplicationtocontinuetothenextmatchingroutewiththeSlimapplications
pass()method.Whenthismethodisinvoked,theSlimapplicationwillimmediatelystopprocessingthe
currentmatchingrouteandinvokethenextmatchingroute.Ifnosubsequentmatchingrouteisfound,a
404NotFoundresponseissenttotheclient.Hereisanexample.AssumeanHTTPrequestforGET
/hello/Frank.
<?php
$app=new\Slim\Slim()
$app>get('/hello/Frank',function()use($app){
echo"Youwon'tseethis..."
$app>pass()
})
$app>get('/hello/:name',function($name)use($app){
echo"Butyouwillseethis!"
})
$app>run()
Redirect
ItiseasytoredirecttheclienttoanotherURLwiththeSlimapplications redirect()method.This
methodacceptstwoarguments:thefirstargumentistheURLtowhichtheclientwillredirectthesecond
optionalargumentistheHTTPstatuscode.Bydefaultthe redirect()methodwillsenda302
TemporaryRedirectresponse.
<?php
$app=new\Slim\Slim()
$app>get('/foo',function()use($app){
$app>redirect('/bar')
})
$app>run()
Orifyouwishtouseapermanentredirect,youmustspecifythedestinationURLasthefirstparameter
andtheHTTPstatuscodeasthesecondparameter.
<?php
$app=new\Slim\Slim()
$app>get('/old',function()use($app){
$app>redirect('/new',301)
})
$app>run()
ThismethodwillautomaticallysettheLocation:header.TheHTTPredirectresponsewillbesenttothe
HTTPclientimmediately.
Stop
TheSlimapplications stop()methodwillstoptheSlimapplicationandsendthecurrentHTTPresponse
totheclientasis.Noifs,ands,orbuts.
<?php
$app=new\Slim\Slim()
$app>get('/foo',function()use($app){
echo"Youwillseethis..."
$app>stop()
echo"Butnotthis"
})
$app>run()
URLFor
TheSlimapplications urlFor()methodletsyoudynamicallycreateURLsforanamedroutesothat,
werearoutepatterntochange,yourURLswouldupdateautomaticallywithoutbreakingyourapplication.
ThisexampledemonstrateshowtogenerateURLsforanamedroute.
<?php
$app=new\Slim\Slim()
//Createanamedroute
$app>get('/hello/:name',function($name)use($app){
echo"Hello$name"
})>name('hello')
//GenerateaURLforthenamedroute
$url=$app>urlFor('hello',array('name'=>'Josh'))
Inthisexample,$urlis/hello/Josh.Tousethe urlFor()method,youmustfirstassignanametoa
route.Next,invokethe urlFor()method.Thefirstargumentisthenameoftheroute,andthesecond
argumentisanassociativearrayusedtoreplacetheroutesURLparameterswithactualvaluesthe
arrayskeysmustmatchparametersintheroutesURIandthevalueswillbeusedassubstitutions.
BacktoTop
RouteURLRewriting
IstronglyencourageyoutouseawebserverthatsupportsURLrewritingthiswillletyouenjoyclean,
humanfriendlyURLswithyourSlimapplication.ToenableURLrewriting,youshouldusetheappropriate
toolsprovidedbyyourwebservertoforwardallHTTPrequeststothePHPfileinwhichyouinstantiate
andrunyourSlimapplication.Thefollowingaresample,bareminimum,configurationsforApachewith
mod_phpandnginx.Thesearenotmeanttobeproductionreadyconfigurationsbutshouldbeenoughto
getyouupandrunning.Toreadmoreonserverdeploymentingeneralyoucancontinuereading
http://www.phptherightway.com(http://www.phptherightway.com).
Apacheandmod_rewrite
Hereisanexampledirectorystructure:
/path/www.mysite.com/
public_html/<Documentroot!
.htaccess
index.php<IinstantiateSlimhere!
lib/
Slim/<IstoreSlimlibfileshere!
The.htaccessfileinthedirectorystructureabovecontains:
RewriteEngineOn
RewriteCond%{REQUEST_FILENAME}!f
RewriteRule^index.php[QSA,L]
Youalsoneedadirectorydirectivetoenable.htaccessfilesandallowtheRewriteEnginedirectivetobe
used.Thisissometimesdonegloballyinthehttpd.conffile,butitsgenerallyagoodideatolimitthe
directivetojustyourvirualhostbyenclosingitinyourVirualHostconfigurationblock.Thisisgenerally
setupinyourconfigurationintheformof:
<VirtualHost*:80>
ServerAdminme@mysite.com
DocumentRoot"/path/www.mysite.com/public_html"
ServerNamemysite.com
ServerAliaswww.mysite.com
#ErrorLog"logs/mysite.comerror.log"
#CustomLog"logs/mysite.comaccess.log"combined
<Directory"/path/www.mysite.com/public_html">
AllowOverrideAll
Orderallow,deny
Allowfromall
</Directory>
</VirtualHost>
Asaresult,Apachewillsendallrequestsfornonexistentfilestomyindex.phpscriptinwhichI
instantiateandrunmySlimapplication.WithURLrewritingenabledandassumingthefollowingSlim
applicationisdefinedinindex.php,youcanaccesstheapplicationroutebelowat/fooratherthan
/index.php/foo.
<?php
$app=new\Slim\Slim()
$app>get('/foo',function(){
echo"Foo!"
})
$app>run()
nginx
Wewillusethesameexampledirectorystructureasbefore,butwithnginxourconfigurationwillgointo
nginx.conf.
/path/www.mysite.com/
public_html/<Documentroot!
index.php<IinstantiateSlimhere!
lib/
Slim/<IstoreSlimlibfileshere!
Hereisasnippetofanginx.confinwhichweusethetry_filesdirectivetoservethefileifitexists,good
forstaticfiles(images,css,jsetc),andotherwiseforwarditontotheindex.phpfile.
server{
listen80
server_namewww.mysite.commysite.com
root/path/www.mysite.com/public_html
try_files$uri/index.php
#thiswillonlypassindex.phptothefastcgiprocesswhichisgenerallysaferbut
#assumesthewholesiteisrunviaSlim.
location/index.php{
fastcgi_connect_timeout3s#defaultof60sisjusttoolong
fastcgi_read_timeout10s#defaultof60sisjusttoolong
includefastcgi_params
fastcgi_pass127.0.0.1:9000#assumesyouarerunningphpfpmlocallyonport90
00
}
}
Mostinstallationswillhaveadefaultfastcgi_paramsfilesetupthatyoucanjustincludeasshownabove.
SomeconfigurationsdontincludetheSCRIPT_FILENAMEparameter.Youmustensureyouincludethis
parameterotherwiseyoumightendupwithaNoinputfilespecifiederrorfromthefastcgiprocess.This
canbedonedirectlyinthelocationblockorsimplyaddedtothefastcgi_paramsfile.Eitherwayitlooks
likethis:
fastcgi_paramSCRIPT_FILENAME$document_root$fastcgi_script_name
WithoutURLRewriting
SlimwillworkwithoutURLrewriting.Inthisscenario,youmustincludethenameofthePHPfileinwhich
youinstantiateandruntheSlimapplicationintheresourceURI.Forexample,assumethefollowingSlim
applicationisdefinedinindex.phpatthetoplevelofyourvirtualhostsdocumentroot:
<?php
$app=new\Slim\Slim()
$app>get('/foo',function(){
echo"Foo!"
})
$app>run()
Youcanaccessthedefinedrouteat/index.php/foo.Ifthesameapplicationisinsteaddefinedin
index.phpinsideofthephysicalsubdirectoryblog/,youcanaccessthedefinedrouteat
/blog/index.php/foo.
BacktoTop
Environment
ocs.slimframework.com/#Environment)
EnvironmentOverview
TheSlimFrameworkimplementsaderivationoftheRackprotocol
(http://rack.rubyforge.org/doc/files/SPEC.html).WhenyouinstantiateaSlimapplication,itimmediately
inspectsthe $_SERVERsuperglobalandderivesasetofenvironmentvariablesthatdictateapplication
behavior.
WhatistheEnvironment?
ASlimapplicationsenvironmentisanassociativearrayofsettingsthatareparsedonceandmade
accessibletotheSlimapplicationanditsmiddleware.Youarefreetomodifytheenvironmentvariables
duringruntimechangeswillpropagateimmediatelythroughouttheapplication.
WhenyouinstantiateaSlimapplication,theenvironmentvariablesarederivedfromthe $_SERVER
superglobalyoudonotneedtosettheseyourself.However,youarefreetomodifyorsupplementthese
variablesinSlimmiddleware.
ThesevariablesarefundamentaltodetermininghowyourSlimapplicationruns:theresourceURI,the
HTTPmethod,theHTTPrequestbody,theURLqueryparameters,erroroutput,andmore.Middleware,
describedlater,givesyouthepowertoamongotherthingsmanipulateenvironmentvariablesbefore
and/oraftertheSlimapplicationisrun.
EnvironmentVariables
Thefollowingtextrespectfullyborrowsthesameinformationoriginallyavailableat
http://rack.rubyforge.org/doc/files/SPEC.html(http://rack.rubyforge.org/doc/files/SPEC.html).The
environmentarraymustincludethesevariables:
REQUEST_METHOD
TheHTTPrequestmethod.Thisisrequiredandmayneverbeanemptystring.
SCRIPT_NAME
TheinitialportionoftherequestURIspaththatcorrespondstothephysicaldirectoryinwhichtheSlim
applicationisinstalledsothattheapplicationknowsitsvirtuallocation.Thismaybeanemptystring
iftheapplicationisinstalledinthetoplevelofthepublicdocumentrootdirectory.Thiswillneverhavea
trailingslash.
PATH_INFO
TheremainingportionoftherequestURIspaththatdeterminesthevirtuallocationoftheHTTP
requeststargetresourcewithintheSlimapplicationcontext.Thiswillalwayshavealeadingslashitmay
ormaynothaveatrailingslash.
QUERY_STRING
ThepartoftheHTTPrequestsURIafter,butnotincluding,the?.Thisisrequiredbutmaybean
emptystring.
SERVER_NAME
Whencombinedwith SCRIPT_NAMEand PATH_INFO,thiscanbeusedtocreateafullyqualifiedURLto
anapplicationresource.However,if HTTP_HOSTispresent,thatshouldbeusedinsteadofthis.Thisis
requiredandmayneverbeanemptystring.
SERVER_PORT
Whencombinedwith SCRIPT_NAMEand PATH_INFO,thiscanbeusedtocreateafullyqualifiedURLto
anyapplicationresource.Thisisrequiredandmayneverbeanemptystring.
HTTP_*
VariablesmatchingtheHTTPrequestheaderssentbytheclient.Theexistenceofthesevariables
correspondwiththosesentinthecurrentHTTPrequest.
slim.url_scheme
WillbehttporhttpsdependingontheHTTPrequestURL.
slim.input
WillbeastringrepresentingtherawHTTPrequestbody.IftheHTTPrequestbodyisempty(e.g.witha
GETrequest),thiswillbeanemptystring.
slim.errors
Mustalwaysbeawritableresourcebydefault,thisisawriteonlyresourcehandleto php://stderr.
TheSlimapplicationcanstoreitsowndataintheenvironment,too.Theenvironmentarrayskeysmust
containatleastonedot,andshouldbeprefixeduniquely(e.g.prefix.foo).Theprefixslim.isreserved
forusebySlimitselfandmustnotbeusedotherwise.Theenvironmentmustnotcontainthekeys
HTTP_CONTENT_TYPEor HTTP_CONTENT_LENGTH(usetheversionswithoutHTTP_).TheCGIkeys(named
withoutaperiod)musthaveStringvalues.Therearethefollowingrestrictions:
slim.url_schememusteitherbehttporhttps.
slim.inputmustbeastring.
Theremustbeavalid,writableresourcein slim.errors.
The REQUEST_METHODmustbeavalidtoken.
The SCRIPT_NAME,ifnonempty,muststartwith/
The PATH_INFO,ifnonempty,muststartwith/
The CONTENT_LENGTH,ifgiven,mustconsistofdigitsonly.
Oneof SCRIPT_NAMEor PATH_INFOmustbeset. PATH_INFOshouldbe/if SCRIPT_NAMEisempty.
SCRIPT_NAMEnevershouldbe/,butinsteadbeanemptystring.
BacktoTop
Request
p://docs.slimframework.com/#Request)
RequestOverview
EachSlimapplicationinstancehasonerequestobject.Therequestobjectisanabstractionofthecurrent
HTTPrequestandallowsyoutoeasilyinteractwiththeSlimapplicationsenvironmentvariables.Although
eachSlimapplicationincludesadefaultrequestobject,the \Slim\Http\Requestclassisidempotentyou
mayinstantiatetheclassatwill(inmiddlewareorelsewhereinyourSlimapplication)withoutaffectingthe
applicationasawhole.YoucanobtainareferencetotheSlimapplicationsrequestobjectlikethis:
<?php
//Returnsinstanceof\Slim\Http\Request
$request=$app>request()
BacktoTop
RequestMethod
EveryHTTPrequesthasamethod(e.g.GETorPOST).YoucanobtainthecurrentHTTPrequestmethod
viatheSlimapplicationsrequestobject:
/**
*Whatistherequestmethod?
*@returnstring(e.g.GET,POST,PUT,DELETE)
*/
$app>request()>getMethod()
/**
*IsthisaGETrequest?
*@returnbool
*/
$app>request()>isGet()
/**
*IsthisaPOSTrequest?
*@returnbool
*/
$app>request()>isPost()
/**
*IsthisaPUTrequest?
*@returnbool
*/
$app>request()>isPut()
/**
*IsthisaDELETErequest?
*@returnbool
*/
$app>request()>isDelete()
/**
*IsthisaHEADrequest?
*@returnbool
*/
$app>request()>isHead()
/**
*IsthisaOPTIONSrequest?
*@returnbool
*/
$app>request()>isOptions()
/**
*IsthisaXHR/AJAXrequest?
*@returnbool
*/
$app>request()>isAjax()
BacktoTop
RequestHeaders
ASlimapplicationwillautomaticallyparseallHTTPrequestheaders.Youcanaccesstherequestheaders
usingtherequestobjects headers()method.
<?php
$app=new\Slim\Slim()
//Getrequestobject
$req=$app>request()
//Getrequestheadersasassociativearray
$headers=$req>headers()
//GettheACCEPT_CHARSETheader
$charset=$req>headers('ACCEPT_CHARSET')
TheHTTPspecificationstatesthatHTTPheadernamesmaybeuppercase,lowercase,ormixedcase.
Slimissmartenoughtoparseandreturnheadervalueswhetheryourequestaheadervalueusingupper,
lower,ormixedcaseheadername,witheitherunderscoresordashes.Sousethenamingconvention
withwhichyouaremostcomfortable.
BacktoTop
RequestBody
Usetherequestobjects getBody()methodtofetchtherawHTTPrequestbodysentbytheHTTPclient.
ThisisparticularlyusefulforSlimapplicationsthatconsumeJSONorXMLrequests.
<?php
$request=$app>request()
$body=$request>getBody()
BacktoTop
RequestVariables
AnHTTPrequestmayhaveassociatedvariables(nottobeconfusedwithroutevariables).TheGET,
POST,orPUTvariablessentwiththecurrentHTTPrequestareexposedviatheSlimapplications
requestobject.
Ifyouwanttoquicklyfetcharequestvariablevaluewithoutconsideringitstype,usetherequestobjects
params()method:
<?php
$req=$app>request()
$paramValue=$req>params('paramName')
The params()methodwillfirstsearchPUTvariables,thenPOSTvariables,thenGETvariables.Ifno
variablesarefound, nullisreturned.Ifyouonlywanttosearchforaspecifictypeofvariable,youcan
usethesemethodsinstead:
<?php
//Getrequestobject
$req=$app>request()
//GETvariable
$paramValue=$req>get('paramName')
//POSTvariable
$paramValue=$req>post('paramName')
//PUTvariable
$paramValue=$req>put('paramName')
Ifavariabledoesnotexist,eachmethodabovewillreturn null.Youcanalsoinvokeanyofthese
functionswithoutanargumenttoobtainanarrayofallvariablesofthegiventype:
<?php
$req=$app>request()
$allGetVars=$req>get()
$allPostVars=$req>post()
$allPutVars=$req>put()
BacktoTop
RequestCookies
GetCookies
ASlimapplicationwillautomaticallyparsecookiessentwiththecurrentHTTPrequest.Youcanfetch
cookievalueswiththeSlimapplications getCookie()methodlikethis:
<?php
$foo=$app>getCookie('foo')
OnlyCookiessentwiththecurrentHTTPrequestareaccessiblewiththismethod.Ifyousetacookie
duringthecurrentrequest,itwillnotbeaccessiblewiththismethoduntilthesubsequentrequest.Ifyou
wanttofetchanarrayofallcookiessentwiththecurrentrequest,youmustusetherequestobjects
cookies()methodlikethis:
<?php
$cookies=$app>request()>cookies()
Whenmultiplecookieswiththesamenameareavailable(e.g.becausetheyhavedifferentpaths)onlythe
mostspecificone(longestmatchingpath)isreturned.SeeRFC2109.
GetEncryptedCookies
Ifyoupreviouslysetanencryptedcookie,youcanfetchitsdecryptedvaluewiththeSlimapplications
getEncryptedCookie()methodlikethis:
<?php
$value=$app>getEncryptedCookie('foo')
IfthecookiewasmodifiedwhilewiththeHTTPclient,Slimwillautomaticallydestroythecookiesvalue
andinvalidatethecookieinthenextHTTPresponse.Youcandisablethisbehaviorbypassing falseas
thesecondargument:
<?php
$value=$app>getEncryptedCookie('foo',false)
Whetheryoudestroyinvalidcookiesornot, nullisreturnedifthecookiedoesnotexistorisinvalid.
BacktoTop
RequestPaths
EveryHTTPrequestreceivedbyaSlimapplicationwillhavearootURIandaresourceURI.
RootURI
TherootURIisthephysicalURLpathofthedirectoryinwhichtheSlimapplicationisinstantiatedandrun.
IfaSlimapplicationisinstantiatedinindex.phpwithinthetopmostdirectoryofthevirtualhosts
documentroot,therootURIwillbeanemptystring.IfaSlimapplicationisinstantiatedandrunin
index.phpwithinaphysicalsubdirectoryofthevirtualhostsdocumentroot,therootURIwillbethepath
tothatsubdirectorywithaleadingslashandwithoutatrailingslash.
ResourceURI
TheresourceURIisthevirtualURIpathofanapplicationresource.TheresourceURIwillbematchedto
theSlimapplicationsroutes.
AssumetheSlimapplicationisinstalledinaphysicalsubdirectory/foobeneathyourvirtualhosts
documentroot.AlsoassumethefullHTTPrequestURL(whatyoudseeinthebrowserlocationbar)is
/foo/books/1.TherootURIis/foo(thepathtothephysicaldirectoryinwhichtheSlimapplicationis
instantiated)andtheresourceURIis/books/1(thepathtotheapplicationresource).
YoucangettheHTTPrequestsrootURIandresourceURIwiththerequestobjects getRootUri()and
getResourceUri()methods:
<?php
$app=newSlim()
//Getrequestobject
$req=$app>request()
//GetrootURI
$rootUri=$req>getRootUri()
//GetresourceURI
$resourceUri=$req>getResourceUri()
BacktoTop
XMLHttpRequest
WhenusingaJavascriptframeworklikeMooToolsorjQuerytoexecuteanXMLHttpRequest,the
XMLHttpRequestwillusuallybesentwithaXRequestedWithHTTPheader.TheSlimapplicationwill
detecttheHTTPrequestsXRequestedWithheaderandflagtherequestassuch.Ifforsomereasonan
XMLHttpRequestcannotbesentwiththeXRequestedWithHTTPheader,youcanforcetheSlim
applicationtoassumeanHTTPrequestisanXMLHttpRequestbysettingaGET,POST,orPUT
parameterintheHTTPrequestnamedisajaxwithatruthyvalue.
<?php
$isXHR=$app>request()>isAjax()
$isXHR=$app>request()>isXhr()
BacktoTop
RequestHelpers
TheSlimapplicationsrequestobjectprovidesseveralhelpermethodstofetchcommonHTTPrequest
information:
ContentType
Fetchtherequestscontenttype(e.g.application/jsoncharset=utf8):
<?php
$req=$app>request()
$req>getContentType()
MediaType
Fetchtherequestsmediatype(e.g.application/json):
<?php
$req=$app>request()
$req>getMediaType()
MediaTypeParams
Fetchtherequestsmediatypeparameters(e.g.[charset=>utf8]):
<?php
$req=$app>request()
$req>getMediaTypeParams()
ContentCharset
Fetchtherequestscontentcharacterset(e.g.utf8):
<?php
$req=$app>request()
$req>getContentCharset()
ContentLength
Fetchtherequestscontentlength:
<?php
$req=$app>request()
$req>getContentLength()
Host
Fetchtherequestshost(e.g.slimframework.com):
<?php
$req=$app>request()
$req>getHost()
HostwithPort
Fetchtherequestshostwithport(e.g.slimframework.com:80):
<?php
$req=$app>request()
$req>getHostWithPort()
Port
Fetchtherequestsport(e.g.80):
<?php
$req=$app>request()
$req>getPort()
Scheme
Fetchtherequestsscheme(e.g.httporhttps):
<?php
$req=$app>request()
$req>getScheme()
Path
Fetchtherequestspath(rootURI+resourceURI):
<?php
$req=$app>request()
$req>getPath()
URL
FetchtherequestsURL(scheme+host[+portifnonstandard]):
<?php
$req=$app>request()
$req>getUrl()
IPAddress
FetchtherequestsIPaddress:
<?php
$req=$app>request()
$req>getIp()
Referer
Fetchtherequestsreferrer:
<?php
$req=$app>request()
$req>getReferrer()
UserAgent
Fetchtherequestsuseragentstring:
<?php
$req=$app>request()
$req>getUserAgent()
BacktoTop
Response
//docs.slimframework.com/#Response)
ResponseOverview
EachSlimapplicationinstancehasoneresponseobject.Theresponseobjectisanabstractionofyour
SlimapplicationsHTTPresponsethatisreturnedtotheHTTPclient.AlthougheachSlimapplication
includesadefaultresponseobject,the \Slim\Http\Responseclassisidempotentyoumayinstantiatethe
classatwill(inmiddlewareorelsewhereinyourSlimapplication)withoutaffectingtheapplicationasa
whole.YoucanobtainareferencetotheSlimapplicationsresponseobjectwith:
<?php
$app>response()
AnHTTPresponsehasthreeprimaryproperties:
Status
Header
Body
Theresponseobjectprovideshelpermethods,describednext,thathelpyouinteractwiththeseHTTP
responseproperties.Thedefaultresponseobjectwillreturna200OKHTTPresponsewiththetext/html
contenttype.
BacktoTop
ResponseStatus
TheHTTPresponsereturnedtotheclientwillhaveastatuscodeindicatingtheresponsestype(e.g.200
OK,400BadRequest,or500ServerError).YoucanusetheSlimapplicationsresponseobjecttosetthe
HTTPresponsesstatuslikethis:
<?php
$app>response()>status(400)
YouonlyneedtosettheresponseobjectsstatusifyouintendtoreturnanHTTPresponsethatdoesnot
havea200OKstatus.YoucanjustaseasilyfetchtheresponseobjectscurrentHTTPstatusbyinvoking
thesamemethodwithoutanargument,likethis:
<?php
$status=$app>response()>status()
BacktoTop
ResponseHeaders
TheHTTPresponsereturnedtotheHTTPclientwillhaveaheader.TheHTTPheaderisalistofkeysand
valuesthatprovidemetadataabouttheHTTPresponse.YoucanusetheSlimapplicationsresponse
objecttosettheHTTPresponsesheader.Theresponseobjectisspecialbecauseitactslikeanarray:
<?php
$res=$app>response()
$res['ContentType']='application/json'
$res['XPoweredBy']='Slim'
Youmayalsofetchheadersfromtheresponseobject:
<?php
$res=$app>response()
$contentType=$response['ContentType']
$poweredBy=$response['XPoweredBy']
Ifaheaderwiththegivennamedoesnotexist, nullisreturned.Youmayspecifyheadernameswith
upper,lower,ormixedcasewithdashesorunderscores.Usethenamingconventionwithwhichyouare
mostcomfortable.
BacktoTop
ResponseBody
TheHTTPresponsereturnedtotheclientwillhaveabody.TheHTTPbodyistheactualcontentofthe
HTTPresponsedeliveredtotheclient.YoucanusetheSlimapplicationsresponseobjecttosetthe
HTTPresponsesbody:
<?php
$res=$app>response()
//Overwriteresponsebody
$res>body('Foo')
//Appendresponsebody
$res>write('Bar')
Whenyouoverwriteorappendtheresponseobjectsbody,theresponseobjectwillautomaticallysetthe
ContentLengthheaderbasedonthebytesizeofthenewresponsebody.
Youcanfetchtheresponseobjectsbodyusingthesame body()methodwithoutanargument:
<?php
$res=$app>response()
$body=$res>body()
BacktoTop
ResponseCookies
TheSlimapplicationprovideshelpermethodstosendcookieswiththeHTTPresponse.
SetCookie
ThisexampledemonstrateshowtousetheSlimapplications setCookie()methodtocreateanHTTP
cookietobesentwiththeHTTPresponse:
<?php
$app>setCookie('foo','bar','2days')
ThiscreatesanHTTPcookiewiththenamefooandvaluebarthatexpirestwodaysfromnow.You
mayalsoprovideadditionalcookieproperties,includingitspath,domain,secure,andhttponlysettings.
TheSlimapplications setCookie()methodusesthesamesignatureasPHPsnative setCookie()
function.
<?php
$app>setCookie(
$name,
$value,
$expiresAt,
$path,
$domain,
$secure,
$httponly
)
SetEncryptedCookie
YoumayalsocreateencryptedcookiesusingtheSlimapplications setEncryptedCookie()method.This
methodactsthesameastheSlimapplications setCookie()methoddemonstratedabove,butitwill
encryptthecookievalueusingtheAES256cipherandyourownsecretkey.Touseencryption,youmust
defineyourencryptionkeywhenyouinstantiateyourSlimapplicationlikethis:
<?php
$app=new\Slim\Slim(array(
'cookies.secret_key'=>'my_secret_key'
))
Ifyouprefer,youmaychangethedefaultcipherandciphermode,too:
<?php
$app=new\Slim\Slim(array(
'cookies.secret_key'=>'my_secret_key',
'cookies.cipher'=>MCRYPT_RIJNDAEL_256,
'cookies.cipher_mode'=>MCRYPT_MODE_CBC
))
Theencryptedcookievalueishashedandlaterverifiedtoensuredataintegritysothatitsvalueisnot
changedwhileontheHTTPclient.
DeleteCookie
YoucandeleteacookieusingtheSlimapplications deleteCookie()method.Thiswillremovethecookie
fromtheHTTPclientbeforethenextHTTPrequest.ThismethodacceptsthesamesignatureastheSlim
applications setCookie()instancemethod,withoutthe $expiresargument.Onlythefirstargumentis
required.
<?php
$app>deleteCookie('foo')
Ifyouneedtoalsospecifythepathanddomain:
<?php
$app>deleteCookie('foo','/','foo.com')
Youmayalsofurtherspecifythesecureandhttponlyproperties:
<?php
$app>deleteCookie('foo','/','foo.com',true,true)
BacktoTop
ResponseHelpers
TheresponseobjectprovideshelpermethodstoinspectandinteractwiththeunderlyingHTTPresponse.
Finalize
Theresponseobjects finalize()methodreturnsanumericarrayof [status,header,body].The
statusisanintegertheheaderisaniterabledatastructureandthebodyisastring.Wereyoutocreatea
new \Slim\Http\ResponseobjectinyourSlimapplicationoritsmiddleware,youwouldcalltheresponse
objects finalize()methodtoproducethestatus,header,andbodyfortheunderlyingHTTPresponse.
<?php
/**
*Preparenewresponseobject
*/
$res=new\Slim\Http\Response()
$res>status(400)
$res>write('Youmadeabadrequest')
$res['ContentType']='text/plain'
/**
*Finalize
*@return[
*200,
*['Contenttype'=>'text/plain'],
*'Youmadeabadrequest'
*]
*/
$array=$res>finalize()
Redirect
Theresponseobjects redirect()methodwillsettheresponsestatusanditsLocation:headerneeded
toreturna3xxRedirectresponse.
<?php
$app>response()>redirect('/foo',303)
StatusIntrospection
Theresponseobjectprovidesotherhelpermethodstoinspectitscurrentstatus.Allofthefollowing
methodsreturnabooleanvalue:
<?php
$res=$app>response()
//Isthisaninformationalresponse?
$res>isInformational()
//Isthisa200OKresponse?
$res>isOk()
//Isthisa2xxsuccessfulresponse?
$res>isSuccessful()
//Isthisa3xxredirectionresponse?
$res>isRedirection()
//Isthisaspecificredirectresponse?(301,302,303,307)
$res>isRedirect()
//Isthisaforbiddenresponse?
$res>isForbidden()
//Isthisanotfoundresponse?
$res>isNotFound()
//Isthisaclienterrorresponse?
$res>isClientError()
//Isthisaservererrorresponse?
$res>isServerError()
BacktoTop
View
(http://docs.slimframework.com/#View)
ViewOverview
ASlimapplicationdelegatesrenderingoftemplatestoitsviewobject.ASlimapplicationviewisasubclass
of \Slim\Viewthatimplementsthisinterface:
<?php
publicrender(string$template)
Theviewobjects rendermethodmustreturntherenderedcontentofthetemplatespecifiedbyits
$templateargument.
BacktoTop
Rendering
YoucanusetheSlimapplications render()methodtoaskthecurrentviewobjecttorenderatemplate
withagivensetofvariables.TheSlimapplications render()methodwill echo()theoutputreturned
fromtheviewobjecttobecapturedbyanoutputbufferandappendedautomaticallytotheresponse
objectsbody.Thisassumesnothingabouthowthetemplateisrenderedthatisdelegatedtotheview
object.
<?php
$app=new\Slim\Slim()
$app>get('/books/:id',function($id)use($app){
$app>render('myTemplate.php',array('id'=>$id))
})
Ifyouneedtopassdatafromtheroutecallbackintotheviewobject,youmustexplicitlydosobypassing
anarrayasthesecondargumentoftheSlimapplications render()methodlikethis:
<?php
$app>render(
'myTemplate.php',
array('name'=>'Josh')
)
YoucanalsosettheHTTPresponsestatuswhenyourenderatemplate:
<?php
$app>render(
'myTemplate.php',
array('name'=>'Josh'),
404
)
BacktoTop
CustomViews
ASlimapplicationdelegatesrenderingoftemplatestoitsviewobject.Acustomviewisasubclassof
\Slim\Viewthatimplementsthisinterface:
<?php
publicrender(string$template)
Theviewobjects rendermethodmustreturntherenderedcontentofthetemplatespecifiedbyits
$templateargument.Whenthecustomviewsrendermethodisinvoked,itispassedthedesired
templatepathname(relativetotheSlimapplicationstemplates.pathsetting)asitsargument.Heresan
examplecustomview:
<?php
classCustomViewextends\Slim\View
{
publicfunctionrender($template)
{
return'Thefinalrenderedtemplate'
}
}
Thecustomviewcandowhateveritwantsinternallysolongasitreturnsthetemplatesrenderedoutput
asastring.AcustomviewmakesiteasytointegratepopularPHPtemplatesystemslikeTwigorSmarty.
HeadsUp!AcustomviewmayaccessdatapassedtoitbytheSlimapplications render()
methodwith $this>data.
YoucanbrowsereadytousecustomviewsthatworkwithpopularPHPtemplateenginesintheSlim
ExtrasrepositoryonGitHub.
ExampleView
<?php
classCustomViewextends\Slim\View
{
publicfunctionrender($template)
{
//$template==='show.php'
//$this>data['title']==='Sahara'
}
}
ExampleIntegration
Ifthecustomviewisnotdiscoverablebyaregisteredautoloader,itmustberequiredbeforetheSlim
applicationisinstantiated.
<?php
require'CustomView.php'
$app=new\Slim\Slim(array(
'view'=>newCustomView()
))
$app>get('/books/:id',function($id)use($app){
$app>render('show.php',array('title'=>'Sahara'))
})
$app>run()
BacktoTop
ViewData
HeadsUp!Rarelywillyousetorappenddatadirectlyontheviewobject.Usually,youpassdata
totheviewwiththeSlimapplications`render()`method.SeeRenderingTemplates(/pages/view
renderingtemplates).
SettingData
Theviewobjects setData()instancemethodwilloverwriteexistingviewdata.Youmayusethismethod
tosetasinglevariabletoagivenvalue:
<?php
$view=$app>view()
$view>setData('color','red')
Theviewsdatawillnowcontainakeycolorwithvaluered.Youmayalsousetheviews setData()
methodtobatchassignanentirearrayofdata:
<?php
$view=$app>view()
$view>setData(array(
'color'=>'red',
'size'=>'medium'
))
Remember,theviews setData()methodwillreplaceallpreviousdata.
AppendingData
Theviewobjectalsohasa appendData()methodthatappendsdatatotheviewsexistingdata.This
methodacceptsanarrayasitsoneandonlyargument:
<?php
$view=$app>view()
$view()>appendData(array(
'foo'=>'bar'
))
BacktoTop
HTTPCaching
http://docs.slimframework.com/#HTTP
Caching)
HTTPCachingOverview
ASlimapplicationprovidesbuiltinsupportforHTTPcachingwithits etag(), lastModified(),and
expires()helpermethods.Itisbesttouseoneof etag()or lastModified()inconjunctionwith
expires()perrouteneveruseboth etag()and lastModified()togetherinthesameroute
callback.
BacktoTop
ETag
ASlimapplicationprovidesbuiltinsupportforHTTPcachingusingETags.AnETagisauniqueidentifier
foraresourceURI.WhenanETagheaderissetwiththeSlimapplications etag()method,theHTTP
clientwillsendanIfNoneMatchheaderwitheachsubsequentHTTPrequestofthesameresourceURI.
IftheETagvaluefortheresourceURImatchestheIfNoneMatchHTTPrequestheader,theSlim
applicationwillreturna304NotModifiedHTTPresponsethatwillprompttheHTTPclienttocontinue
usingitscachethisalsopreventstheSlimapplicationfromservingtheentiremarkupfortheresource
URI,savingbandwidthandresponsetime.
SettinganETagwithSlimisverysimple.InvoketheSlimapplications etag()methodinyourroute
callback,passingitauniqueIDasthefirstandonlyargument.
<?php
$app>get('/foo',function()use($app){
$app>etag('uniqueid')
echo"Thiswillbecachedaftertheinitialrequest!"
})
Thatsit.MakesuretheETagIDisuniqueforthegivenresource.AlsomakesuretheETagIDchanges
asyourresourcechangesotherwise,theHTTPclientwillcontinueservingitsoutdatedcache.
BacktoTop
LastModified
ASlimapplicationprovidesbuiltinsupportforHTTPcachingusingtheresourceslastmodifieddate.
Whenyouspecifyalastmodifieddate,SlimtellstheHTTPclientthedateandtimethecurrentresource
waslastmodified.TheHTTPclientwillthensendaIfModifiedSinceheaderwitheachsubsequent
HTTPrequestforthegivenresourceURI.IfthelastmodificationdateyouspecifymatchestheIf
ModifiedSinceHTTPrequestheader,theSlimapplicationwillreturna304NotModifiedHTTP
responsethatwillprompttheHTTPclienttouseitscachethisalsopreventstheSlimapplicationfrom
servingtheentiremarkupfortheresourceURIsavingbandwidthandresponsetime.
SettingalastmodifieddatewithSlimisverysimple.YouonlyneedtoinvoketheSlimapplications
lastModified()methodinyourroutecallbackpassinginaUNIXtimestampofthelastmodificationdate
forthegivenresource.Besurethe lastModified()methodstimestampupdatesalongwiththe
resourceslastmodificationdateotherwise,thebrowserclientwillcontinueservingitsoutdatedcache.
<?php
$app>get('/foo',function()use($app){
$app>lastModified(1286139652)
echo"Thiswillbecachedaftertheinitialrequest!"
})
BacktoTop
Expires
UsedinconjunctionwiththeSlimapplications etag()or lastModified()methods,the expires()
methodsetsanExpiresheaderontheHTTPresponseinformingtheHTTPclientwhenitsclientside
cacheforthecurrentresourceshouldbeconsideredstale.TheHTTPclientwillcontinueservingfromits
clientsidecacheuntiltheexpirationdateisreached,atwhichtimetheHTTPclientwillsendaconditional
GETrequesttotheSlimapplication.
The expires()methodacceptsoneargument:anintegerUNIXtimestamp,orastringtobeparsedwith
strtotime().
<?php
$app>get('/foo',function()use($app){
$app>etag('uniqueresourceid')
$app>expires('+1week')
echo"Thiswillbecachedclientsideforoneweek"
})
BacktoTop
Middleware
docs.slimframework.com/#Middleware)
MiddlewareOverview
TheSlimFrameworkimplementsaversionoftheRackprotocol.Asaresult,aSlimapplicationcanhave
middlewarethatmayinspect,analyze,ormodifytheapplicationenvironment,request,andresponse
beforeand/oraftertheSlimapplicationisinvoked.
MiddlewareArchitecture
ThinkofaSlimapplicationasthecoreofanonion.Eachlayeroftheonionismiddleware.Whenyou
invoketheSlimapplications run()method,theoutermostmiddlewarelayerisinvokedfirst.When
ready,thatmiddlewarelayerisresponsibleforoptionallyinvokingthenextmiddlewarelayerthatit
surrounds.ThisprocessstepsdeeperintotheonionthrougheachmiddlewarelayeruntilthecoreSlim
applicationisinvoked.Thissteppedprocessispossiblebecauseeachmiddlewarelayer,andtheSlim
applicationitself,allimplementapublic call()method.WhenyouaddnewmiddlewaretoaSlim
application,theaddedmiddlewarewillbecomeanewouterlayerandsurroundthepreviousouter
middlewarelayer(ifavailable)ortheSlimapplicationitself.
ApplicationReference
Thepurposeofmiddlewareistoinspect,analyze,ormodifytheapplicationenvironment,request,and
responsebeforeand/oraftertheSlimapplicationisinvoked.Itiseasyforeachmiddlewaretoobtain
referencestotheprimarySlimapplication,itsenvironment,itsrequest,anditsresponse:
<?php
classMyMiddlewareextends\Slim\Middleware
{
publicfunctioncall()
{
//TheSlimapplication
$app=$this>app
//TheEnvironmentobject
$env=$app>environment()
//TheRequestobject
$req=$app>request()
//TheResponseobject
$res=$app>response()
}
}
Changesmadetotheenvironment,request,andresponseobjectswillpropagateimmediatelythroughout
theapplicationanditsothermiddlewarelayers.Thisispossiblebecauseeverymiddlewarelayerisgiven
areferencetothesameSlimapplicationobject.
NextMiddlewareReference
Eachmiddlewarelayeralsohasareferencetothenextinnermiddlewarelayerwith $this>next.Itis
eachmiddlewaresresponsibilitytooptionallycallthenextmiddleware.DoingsowillallowtheSlim
applicationtocompleteitsfulllifecycle.Ifamiddlewarelayerchoosesnottocallthenextinner
middlewarelayer,furtherinnermiddlewareandtheSlimapplicationitselfwillnotberun,andthe
applicationresponsewillbereturnedtotheHTTPclientasis.
<?php
classMyMiddlewareextends\Slim\Middleware
{
publicfunctioncall()
{
//Optionallycallthenextmiddleware
$this>next>call()
}
}
BacktoTop
HowtoUseMiddleware
UsetheSlimapplications add()instancemethodtoaddnewmiddlewaretoaSlimapplication.New
middlewarewillsurroundpreviouslyaddedmiddleware,ortheSlimapplicationitselfifnomiddlewarehas
yetbeenadded.
ExampleMiddleware
ThisexamplemiddlewarewillcapitalizetheSlimapplicationsHTTPresponsebody.
<?php
classAllCapsMiddlewareextends\Slim\Middleware
{
publicfunctioncall()
{
//Getreferencetoapplication
$app=$this>app
//Runinnermiddlewareandapplication
$this>next>call()
//Capitalizeresponsebody
$res=$app>response()
$body=$res>body()
$res>body(strtoupper($body))
}
}
AddMiddleware
<?php
$app=new\Slim\Slim()
$app>add(new\AllCapsMiddleware())
$app>get('/foo',function()use($app){
echo"Hello"
})
$app>run()
TheSlimapplications add()methodacceptsoneargument:amiddlewareinstance.Ifthemiddleware
instancerequiresspecialconfiguration,itmayimplementitsownconstructorsothatitmaybeconfigured
beforeitisaddedtotheSlimapplication.
WhentheexampleSlimapplicationaboveisrun,theHTTPresponsebodywillbeanenthusiastic
HELLO
BacktoTop
HowtoWriteMiddleware
Slimapplicationmiddlewaremustsubclass \Slim\Middlewareandimplementapublic call()method.
The call()methoddoesnotacceptarguments.Middlewaremayimplementitsownconstructor,
properties,andmethods.IencourageyoutolookatSlimsbuiltinmiddlewareforworkingexamples(e.g.
Slim/Middleware/ContentTypes.phporSlim/Middleware/SessionCookie.php).
ThisexampleisthemostsimpleimplementationofSlimapplicationmiddleware.Itextends
\Slim\Middleware,implementsapublic call()method,andcallsthenextinnermiddleware.
<?php
classMyMiddlewareextends\Slim\Middleware
{
publicfunctioncall()
{
$this>next>call()
}
}
BacktoTop
Hooks
ttp://docs.slimframework.com/#Hooks)
HooksOverview
ASlimapplicationprovidesasetofhookstowhichyoucanregisteryourowncallbacks.
Whatisahook?
AhookisamomentintheSlimapplicationlifecycleatwhichaprioritylistofcallablesassignedtothe
hookwillbeinvoked.Ahookisidentifiedbyastringname.
BacktoTop
HowtoUseHooks
AcallableisassignedtoahookusingtheSlimapplications hook()method:
<?php
$app=new\Slim\Slim()
$app>hook('the.hook.name',function(){
//Dosomething
})
Thefirstargumentisthehookname,andthesecondargumentisthecallable.Eachhookmaintainsa
prioritylistofregisteredcallables.Bydefault,eachcallableassignedtoahookisgivenapriorityof10.
Youcangiveyourcallableadifferentprioritybypassinganintegerasthethirdparameterofthe hook()
method:
<?php
$app=new\Slim\Slim()
$app>hook('the.hook.name',function(){
//Dosomething
},5)
Theexampleaboveassignsapriorityof5tothecallable.Whenthehookiscalled,itwillsortallcallables
assignedtoitbypriority(ascending).Acallablewithpriority1willbeinvokedbeforeacallablewithpriority
10.
Hooksdonotpassargumentstotheircallables.IfacallableneedstoaccesstheSlimapplication,youcan
injecttheapplicationintothecallbackwiththe usekeywordorwiththeSlimapplicationsstatic
getInstance()method:
<?php
$app=new\Slim\Slim()
$app>hook('the.hook.name',function()use($app){
//Dosomething
})
BacktoTop
DefaultHooks
ThesearethedefaulthooksalwaysinvokedinaSlimapplication.
slim.before
ThishookisinvokedbeforetheSlimapplicationisrunandbeforeoutputbufferingisturnedon.This
hookisinvokedonceduringtheSlimapplicationlifecycle.
slim.before.router
Thishookisinvokedafteroutputbufferingisturnedonandbeforetherouterisdispatched.Thishookis
invokedonceduringtheSlimapplicationlifecycle.
slim.before.dispatch
Thishookisinvokedbeforethecurrentmatchingrouteisdispatched.Usuallythishookisinvokedonly
onceduringtheSlimapplicationlifecyclehowever,thishookmaybeinvokedmultipletimesifa
matchingroutechoosestopasstoasubsequentmatchingroute.
slim.after.dispatch
Thishookisinvokedafterthecurrentmatchingrouteisdispatched.Usuallythishookisinvokedonly
onceduringtheSlimapplicationlifecyclehowever,thishookmaybeinvokedmultipletimesifa
matchingroutechoosestopasstoasubsequentmatchingroute.
slim.after.router
Thishookisinvokedaftertherouterisdispatched,beforetheResponseissenttotheclient,andafter
outputbufferingisturnedoff.ThishookisinvokedonceduringtheSlimapplicationlifecycle.
slim.after
ThishookisinvokedafteroutputbufferingisturnedoffandaftertheResponseissenttotheclient.This
hookisinvokedonceduringtheSlimapplicationlifecycle.
BacktoTop
CustomHooks
CustomhooksmaybecreatedandinvokedinaSlimapplication.Whenacustomhookisinvokedwith
applyHook(),itwillinvokeallcallablesassignedtothathook.ThisisexactlyhowtheSlimapplications
defaulthookswork.Inthisexample,Iapplyacustomhookcalledmy.hook.name.Allcallablespreviously
registeredforthishookwillbeinvoked.
<?php
$app=new\Slim\Slim()
$app>applyHook('my.hook.name')
Whenyouruntheabovecode,anycallablespreviouslyassignedtothehookmy.hook.namewillbe
invokedinorderofpriority(ascending).
Youshouldregistercallablestoahookbeforethehookisapplied.Thinkofitthisway:whenyouinvoke
theSlimapplications applyHook()method,youareaskingSlimtoinvokeallcallablesalreadyregistered
forthathookname.
BacktoTop
FlashMessages
http://docs.slimframework.com/#Flash
Messages)
FlashMessagingOverview
HeadsUp!Flashmessagesrequiresessions.Ifyoudonotusethe
\Slim\Middleware\SessionCookiemiddleware,youmuststartanativePHPsessionyourself.
SlimsupportsflashmessagingmuchlikeRailsandotherlargerwebframeworks.Flashmessagingallows
youtodefinemessagesthatwillpersistuntilthenextHTTPrequestbutnofurther.Thisishelpfulto
displaymessagestotheuserafteragiveneventorerroroccurs.
BacktoTop
FlashNext
TheSlimapplications flash()methodsetsamessagethatwillbeavailableinthenextrequestsview
templates.Themessageinthisexamplewillbeavailableinthetemplatevariable flash['error'].
<?php
$app>flash('error','Useremailisrequired')
BacktoTop
FlashNow
TheSlimapplications flashNow()methodsetsamessagethatwillbeavailableinthecurrentrequests
viewtemplates.Messagessetwiththe flashNow()applicationinstancemethodwillnotbeavailablein
thenextrequest.Themessageintheexamplebelowwillbeavailableinthetemplatevariable
flash['info'].
<?php
$app>flashNow('info','Yourcreditcardisexpired')
BacktoTop
FlashKeep
ThismethodtellstheSlimapplicationtokeepexistingflashmessagessetinthepreviousrequestsothey
willbeavailabletothenextrequest.ThismethodishelpfulforpersistingflashmessagesacrossHTTP
redirects.
<?php
$app>flashKeep()
BacktoTop
Sessions
://docs.slimframework.com/#Sessions)
NativeSessionStore
ASlimapplicationdoesnotpresumeanythingaboutsessions.IfyouprefertouseaPHPsession,you
mustconfigureandstartanativePHPsessionwith session_start()beforeyouinstantiatetheSlim
application.
YoushouldalsodisablePHPssessioncachelimitersothatPHPdoesnotsendconflictingcache
expirationheaderswiththeHTTPresponse.YoucandisablePHPssessioncachelimiterwith:
<?php
session_cache_limiter(false)
session_start()
BacktoTop
CookieSessionStore
Youmayalsousethe \Slim\Middleware\SessionCookiemiddlewaretopersistsessiondatainencrypted,
hashedHTTPcookies.Toenablethesessioncookiemiddleware,addthe
\Slim\Middleware\SessionCookiemiddlewaretoyourSlimapplication:
<?php
$app=newSlim()
$app>add(new\Slim\Middleware\SessionCookie(array(
'expires'=>'20minutes',
'path'=>'/',
'domain'=>null,
'secure'=>false,
'httponly'=>false,
'name'=>'slim_session',
'secret'=>'CHANGE_ME',
'cipher'=>MCRYPT_RIJNDAEL_256,
'cipher_mode'=>MCRYPT_MODE_CBC
)))
Thesecondargumentisoptionalitisshownheresoyoucanseethedefaultmiddlewaresettings.The
sessioncookiemiddlewarewillworkseamlesslywiththe $_SESSIONsuperglobalsoyoucaneasily
migratetothissessionstoragemiddlewarewithzerochangestoyourapplicationcode.
Ifyouusethesessioncookiemiddleware,youDONOTneedtostartanativePHPsession.The
$_SESSIONsuperglobalwillstillbeavailable,anditwillbepersistedintoanHTTPcookieviathe
middlewarelayerratherthanwithPHPsnativesessionmanagement.
Remember,HTTPcookiesareinherentlylimitedtoonly4kilobytesofdata.Ifyourencryptedsessiondata
willexceedthislength,youshouldinsteadrelyonPHPsnativesessionsoranalternatesessionstore.
BacktoTop
Logging
p://docs.slimframework.com/#Logging)
Overview
ASlimapplicationprovidesalogobjectthatwritesdatatoaspecificoutput.Theactualwritingofdatais
delegatedtoalogwriter.
Howtologdata
TologdatainaSlimapplication,getareferencetothelogobject:
<?php
$log=$app>getLog()
Thelogobjectprovidesthefollowinginterface:
$log>debug(mixed$object)
$log>info(mixed$object)
$log>warn(mixed$object)
$log>error(mixed$object)
$log>fatal(mixed$object)
Eachlogobjectmethodacceptsonemixedargument.Theargumentisusuallyastring,buttheargument
canbeanything.Thelogobjectwillpasstheargumenttoitslogwriter.Itisthelogwritersresponsibilityto
writearbitraryinputtotheappropriatedestination.
BacktoTop
ActivateLogging
TheSlimapplicationslogobjectprovidesthefollowingpublicmethodstoenableordisableloggingduring
runtime.
<?php
//Enablelogging
$app>getLog()>setEnabled(true)
//Disablelogging
$app>getLog()>setEnabled(false)
Youmayenableordisablethelogobjectduringapplicationinstantiationlikethis:
<?php
$app=newSlim(array(
'log.enabled'=>true
))
Ifloggingisdisabled,thelogobjectwillignoreallloggedmessagesuntilitisenabled.
BacktoTop
LogLevels
HeadsUp!Usethe \Slim\Logconstantswhensettingtheloglevelinsteadofusingrawintegers.
TheSlimapplicationslogobjectwillrespectorignoreloggedmessagesbasedonitsloglevelsetting.
Whenyouinvokethelogobjectss debug(), info(), warn(), error(),or fatal()methods,youare
inherentlyassigningaleveltotheloggedmessage.Theavailableloglevelsare:
\Slim\Log::DEBUG
Level4
\Slim\Log::INFO
Level3
\Slim\Log::WARN
Level2
\Slim\Log::ERROR
Level1
\Slim\Log::FATAL
Level0
Onlymessagesthathavealevellessthanthecurrentlogobjectslevelwillbelogged.Forexample,ifthe
logobjectslevelis \Slim\Log::WARN(2),thelogobjectwillignore \Slim\Log::DEBUGand
\Slim\Log::INFOmessagesbutwillaccept \Slim\Log::WARN, \Slim\Log::ERROR,and
\Slim\Log::FATALmessages.
Howtosettheloglevel
<?php
$log=$app>getLog()
$log>setLevel(\Slim\Log::WARN)
Youcansetthelogobjectslevelduringapplicationinstantiation,too:
<?php
$app=new\Slim\Slim(array(
'log.level'=>\Slim\Log::WARN
))
BacktoTop
LogWriters
TheSlimapplicationslogobjecthasalogwriter.Thelogwriterisresponsibleforsendingalogged
messagetotheappropriateoutput(e.g.STDERR,alogfile,aremotewebservice,Twitter,ora
database).Outofthebox,theSlimapplicationslogobjecthasalogwriterofclass
\Slim\LogFileWriterthislogwriterdirectsoutputtotheresourcehandlereferencedbytheapplication
environmentsslim.errorskey(bydefault,thisisphp://stderr).Youmayalsodefineanduseacustom
logwriter.
Howtouseacustomlogwriter
Acustomlogwritermustimplementthefollowingpublicinterface:
<?php
publicfunctionwrite(mixed$message)
YoumusttelltheSlimapplicationslogobjecttouseyourcustomlogwriter.Youcandosoinyour
applicationssettingsduringinstantiationlikethis:
<?php
$app=new\Slim\Slim(array(
'log.writer'=>newMyLogWriter()
))
Youmayalsosetacustomlogwriterwithmiddlewarelikethis:
<?php
classCustomLogWriterMiddlewareextends\Slim\Middleware
{
publicfunctioncall()
{
//Setthenewlogwriter
$log=$this>app>getLog()
$log>setWriter(new\MyLogWriter())
//Callnextmiddleware
$this>next>call()
}
}
Youcansetthelogwritersimilarlyinanapplicationhookorroutecallbacklikethis:
<?php
$app>hook('slim.before',function()use($app){
$app>getLog()>setWriter(new\MyLogWriter())
})
Ifyouonlyneedtoredirecterroroutputtoadifferentresourcehandle,usetheSlimapplicaitonsdefault
logwriteritwriteslogmessagestoaresourcehandle.Allyouneedtodoissettheslim.errors
environmentvariabletoavalidresourcehandle.
BacktoTop
ErrorHandling
http://docs.slimframework.com/#Error
Handling)
Overview
Letsfaceit:sometimesthingsgowrong.Itisimportanttointercepterrorsandrespondtothem
appropriately.ASlimapplicationprovideshelpermethodstorespondtoerrorsandexceptions.
ImportantNotes
ASlimapplicationrespectsyourexisting error_reportingsetting
ASlimapplicationonlyhandleserrorsandexceptionsgeneratedinsidetheSlimapplication
ASlimapplicationconvertserrorsinto ErrorExceptionobjectsandthrowsthem
ASlimapplicationusesitsbuiltinerrorhandlerifits debugsettingistrueotherwise,itusesthe
customerrorhandler.
BacktoTop
ErrorHandler
YoumayusetheSlimapplications error()methodtospecifyacustomerrorhandlertobeinvoked
whenanerrororexceptionoccurs.Customerrorhandlersareonlyinvokedifapplicationdebuggingis
disabled.
Acustomerrorhandlershouldrenderauserfriendlymessagethatmitigatesuserconfusion.Similarto
theSlimapplications notFound()method,the error()methodactsasbothagetterandasetter.
Setcustomerrorhandler
YoumaysetacustomerrorhandlerbypassingacallableintotheSlimapplications error()methodas
itsfirstandonlyargument.
<?php
$app=new\Slim\Slim()
$app>error(function(\Exception$e)use($app){
$app>render('error.php')
})
Inthisexample,thecustomerrorhandleracceptsthecaughtExceptionasitsargument.Thisallowsyou
torespondappropriatelytodifferentexceptions.
Invokecustomerrorhandler
Usually,theSlimapplicationwillautomaticallyinvoketheerrorhandlerwhenanexceptionorerroroccurs.
However,youmayalsomanuallyinvoketheerrorhandlerwiththeSlimapplications error()method
(withoutanargument).
BacktoTop
NotFoundHandler
Itisaninevitabilitythatsomeonewillrequestapagethatdoesnotexist.TheSlimapplicationletsyou
easilydefineacustomNotFoundhandlerwiththeSlimapplications notFound()method.TheNotFound
handlerwillbeinvokedwhenamatchingrouteisnotfoundforthecurrentHTTPrequest.Thismethod
actsasbothagetterandasetter.
Setnotfoundhandler
IfyouinvoketheSlimapplications notFound()methodandspecifyacallableobjectasitsfirstandonly
argument,thismethodwillregisterthecallableobjectastheNotFoundhandler.However,theregistered
handlerwillnotbeinvoked.
<?php
$app=new\Slim\Slim()
$app>notFound(function()use($app){
$app>render('404.html')
})
Invokenotfoundhandler
IfyouinvoketheSlimapplications notFound()methodwithoutanyarguments,thismethodwillinvoke
thepreviouslyregisteredNotFoundhandler.
<?php
$app=new\Slim\Slim()
$app>get('/hello/:name',function($name)use($app){
if($name==='Waldo'){
$app>notFound()
}else{
echo"Hello,$name"
}
})
BacktoTop
Debugging
Youcanenabledebuggingduringapplicationinstantiationwiththissetting:
<?php
$app=new\Slim\Slim(array(
'debug'=>true
))
YoumayalsoenabledebuggingduringruntimewiththeSlimapplications config()instancemethod:
<?php
$app=new\Slim\Slim()
//Enabledebugging(onbydefault)
$app>config('debug',true)
//Disabledebugging
$app>config('debug',false)
Ifdebuggingisenabledandanexceptionorerroroccurs,adiagnosticscreenwillappearwiththeerror
description,theaffectedfile,thefilelinenumber,andastacktrace.Ifdebuggingisdisabled,thecustom
Errorhandlerwillbeinvokedinstead.
BacktoTop
OutputRedirection
TheSlimapplicationsenvironmentwillalwayscontainakeyslim.errorswithavaluethatisawritable
resourcetowhichloganderrormessagesmaybewritten.TheSlimapplicationslogobjectwillwritelog
messagestoslim.errorswheneveranExceptioniscaughtorthelogobjectismanuallyinvoked.
Ifyouwanttoredirecterroroutputtoadifferentlocation,youcandefineyourownwritableresourceby
modifyingtheSlimapplicationsenvironmentsettings.Irecommendyouusemiddlewaretoupdatethe
environment:
<?php
classCustomErrorMiddlewareextends\Slim\Middleware
{
publicfunctioncall()
{
//Setnewerroroutput
$env=$this>app>environment()
$env['slim.errors']=fopen('/path/to/output','w')
//Callnextmiddleware
$this>next>call()
}
}
Remember,slim.errorsdoesnothavetopointtoafileitcanpointtoanyvalidwritableresource.
BacktoTop