Professional Documents
Culture Documents
KohanaisaPHP5frameworkthatusestheModelViewControllerarchitecturalpattern.Itaimsto besecure,lightweight,andeasytouse.
Features
1. StrictPHP5OOP.Offersmanybenefits:visibilityprotection,automaticclassloading, overloading,interfaces,abstracts,singletons,etc. 2. Community,notcompany,driven.Kohanaisdrivenbycommunitydiscussion,ideas,and code.Kohanadevelopersarefromallaroundtheworld,eachwiththeirowntalents.This allowsarapidandflexibledevelopmentcyclethatcanrespondtonewbugsandrequests withinhours. 3. GET,POST,COOKIE,andSESSIONarraysallworkasexpected.Kohanadoesnot limityouraccesstoglobaldata,butprovidesXSSfilteringandsanitycheckingofallglobal data. 4. Cascadingresources,modules,andinheritance.Controllers,models,libraries,helpers, andviewscanbeloadedfromanylocationwithinyoursystem,application,ormodulepaths. Configurationoptionsareinheritedandcanbydynamicallyoverwrittenbyeachapplication. 5. Nonamespaceconflicts.Classsuffixesandprefixesareusedtopreventnamespace conflicts. 6. Autoloadingofclasses.AllclassesinKohanaareautomaticallyloadedbytheframework, andneverhavetobemanuallyincluded. 7. APIconsistency.Classesthatrequireaccesstodifferentprotocolsusedriverstokeepthe thevisibleAPIcompletelyconsistent,evenwhenthebackendchanges. 8. Powerfuleventhandler.Kohanaeventscantransparentlybe:added,replaced,oreven removedcompletely.
Goals
Tobesecuremeanstousebestpracticesregardingsecurity,atalltimes:
KohanacomeswithbuiltinXSSprotection,andcanalsouseHTMLPurfierasanXSSfilter. Alldatainsertedintothedatabaseisescapedusingdatabasespecificfunctions,like mysql_real_escape_string,toprotectagainstSQLinjectionattacks.magicquotesare disabledbyKohana. AllPOST,GET,andCOOKIEdataissanitizedtopreventmaliciousbehavior. Kohanausesconventionoverconfigurationasmuchaspossible. SanedefaultsandhighlyoptimizedenvironmentdetectionroutinesallowKohanatorunin almostanyPHP5environment. Loosecoupling isusedtoalwaysloadtheminimumnumberoffiles,reducingresource usage. AcleanAPIandusingnativefunctionswheneverpossiblemakesKohanaoneofthefastest PHP5frameworksavailable.
Tobelightweightmeanstoprovidethehighestamountofflexibilityinthemostefficientmanner:
TobeeasytousemeanstoprovideunderstandableAPIandusagedocumentation,basedon
communityfeedback.
MVC
KohanausestheModelViewControllerarchitecturalpattern.Thiskeepsapplicationlogicseparate fromthepresentationandallowsforcleanerandeasiertoworkwithcode. InKohanathismeans:
Features
Technology
Credits
MostoftheKohanasourcecodeiswrittenbytheKohanaTeam.Thereareafewnotablecredits, however.
CodeIgniter
KohanawasoriginallyaforkofCodeIgniter(CI),whichisanopensourceproductofEllisLab. TherearestillmanysimilaritiesbetweenCIandKohana,particularlyinnamingconventionsand filesystemdesign,butallofthecodeiseitherneworcompletelyrewritten. CodeIgniteris2006EllisLab,Inc.
phputf8
AlloftheKohanaUTF8functionsareportedfromthephputf8project.
phputf8is2005HarryFuecks.
Popoon
ThedefaultXSSfilterusedbyKohanawasoriginallycreatedbyChristianStockerforthepopoon framework.Theoriginalfileiscalledexternalinput.php. popoonis20012006BitfluxGmbH
HTMLPurifier
ThealternativeXSSfilterusedbyKohanaisHTMLPurifier.Thisisanoptionaldownload. HTMLPurifieris20062007EdwardZ.Yang
SwiftMailer
TherecommendedwaytosendemailsinKohanaisusingSwiftMailer.Thisisanoptional download. SwiftMailerisChrisCorbyn
PHPMarkdown
MarkdownisasimpletexttoHTMLformattingtool.KohanaincludesPHPMarkdownasan optionaldownload. PHPMarkdownis2006MichelFortin Those who cannot remember the past are condemned to repeat it. GeorgeSantayana
History
ThehistoryofKohanaistoldbackwards,becausewearelookingforward.
Kohana2.1.x
February7,2008ReleaseofKohana2.1.1 February5,2008ReleaseofKohana2.1
Kohana2.0
November2007 Kohanaversion2.0isreleased.PHP5based.NewfullyOOPframework,nolegacycode,includes modules,builtonthecascadingresourcesconcept.
TheGoodOldDays
SeptemberOctober2007
WegetaBDFL,decisiontogoPHP5only,newlife,newgoals.Almosttotalrewriteundertakenby developers.(Allthreeofthem)
TheWorstofTimes
August2007.OurProjectleadergoeswalkabout,notmuchhappens.
Kohana1.0
JuneJuly2007Kohanaisrereleasedasversion1.0,withoutdocumentation. Lotsofideasanddiscussionsonthewayforward,
Kohana
June2007. AnewName,forum,Trac.
InTheBeginning
BlueFlame,acommunity forkofCodeIgniterisreleased. Reactionsandresponses.Theforksplits. May312007BlueFlameannounced
BeforeTheBeginning
UpuntilMay2007 ThefoundingmembersofKohanaarefromtheCodeignitercommunity. Ourinitialhappiness,andlaterunhappiness,withCI.
BasicRequirements
Kohanawillruninalmostanyenvironmentwithminimalconfiguration.Thereareafewminimum serverrequirements: 1. ServerwithUnicodesupport 2. PHPversion>=5.1.3 3. AnHTTPserver.Kohanaisknowntoworkwith:Apache1.3+,Apache2.0+,lighttpd,and MSIIS Optionally,ifyouwishtouseadatabasewithKohana,youwillneedadatabaseserver.Thereare databasedriversforMySQLandPostgreSQL,withadditiondriversplanned.
RequiredExtensions
1. PCRE mustbecompiledwithenable-utf8andenable-unicode-properties forUTF8functionstoworkproperly.
RecommendedExtensions
1. mbstring willdramaticallyspeedupKohana'sUTF8functions.However,notethatthe mbstringextensionmustnotbeoverloadingPHP'snativestringfunctions!
InstallKohana
Kohanaisinstalledinseveraleasysteps: 1. Download acopyofKohana. 2. Unzipthepackageyoudownloaded.Thisshouldcreateakohanadirectory. 3. UploadtheKohanafilestoyourwebserver,placingindex.phpinthedirectorythatyou wouldlikeKohanaaccessiblefrom. 4. Edittheglobalconfigurationfileapplication/config/config.php 5. Maketheapplication/logsdirectorywriteable.Chmodto666. 6. Maketheapplication/cachedirectorywriteableifyouusethecachelibrary.Chmod to666. 7. TestyourinstallationbyopeningtheURLyousetasthebase_urlinyourfavorite browser IfyouseetheWelcomepage,yourKohanainstallationiscomplete!
Removingindex.phpfromURL's
IfyouwantreallycleanURL'sandthereforeremovetheindex.phpineachURLthisispossible.
TutorialRemoveindex.phpforApachewebserver
AdditionalConfiguration
Youcanprovideyourinstallationwithadditionalconfigurationbycopyingfilesfromthesystem/ configdirectorytotheapplication/configdirectory.Forexampleifyouwantto configureadatabaseconnection,youcancopyoversystem/config/database.phpto application/config/database.phpandeditthedatabaseconnectiondetails.
Afterinstallation
Afterinstallationyou'rereadytobuildyourfirstwebapplicationwithKohana.Ifyou'renewto Kohanayoushouldfirstreadallarticlesintheuserguideunderthe'General'section.
ExperiencingProblems?
IfyouwerenotabletoviewtheKohanaWelcomepageonyourserverafterinstalling,pleaseread theTroubleshootingpageoftheuserguide,visittheKohanaWiki,oraskforassistanceinthe communityforums.
[moveTo:Troubleshooting]TheKohanaTeamtriestomakesurethatKohanaisasfreefrombugsas possible.Ifyouhavefoundabug,pleasereportit.
ForExperiencedUsers
TouseamultisiteKohanainstall,simplyfollowthesesteps. 1. Download acopyofKohana. 2. Putthesystemfoldersomewhereonyourserver,preferablyoutsideofyourwebserver's documentroot. 3. Deletethesystemfolderinyourcurrentapplication. 4. Foryourapplication'sindex.phpfile,changethe$kohana_systemvariabletothe relativeorabsolutepathofwhereyouputthesystemfolder. 5. Youcannowpointallofyourapplicationstothisonesystemfolderforeasyupgrades.This makesyourlifeawholeloteasierwhenyouhave10+kohanasitesonyourserver.
Movingsystemandapplicationdirectoryoutofwebroot
'webroot'isdefinedasthetopleveldirectorytowhichawebserverwillallowpublicaccess.A correctlyconfiguredserverwillnotallowpublicaccesstofilesordirectoriesabovewebrootinthe directorytree. Itisconsideredagoodsecuritypracticetomoveapplication,systemandmodulesoutof thewebroot,topreventpotentialpublicaccess,shouldPHPbedisabled,oryourwebserveris compromised.Kohanaenablesyoutoplacetheindex.phpinthewebroot,andallotherfilesoutside ofit.Staticcontent,suchasstylesheet,imageandjavascriptfiles,aretypicallyplacedwithin webroot. Inafewstepsthiscanbeaccomplished 1. Movethedirectoriesoutofthewebrootbutleaveindex.phpin 2. Openindex.phpfileinaneditor 3. Setthevariable$kohana_applicationtotheapplicationdirectoryyou'reusing(must containconfig/config.phpfile) 4. Setthevariable$kohana_systemtothesystemdirectoryyou'reusing Notethatmovingthesystemdirectoryoutofwebroot,alsomakesitmoreeasilyaccessibleby multipleKohanaapplications.Soyoucanusethesamesystemformultipleapplications.This allowsforeasyupgrades.Simplyrefertothesamesysteminthe$kohana_systeminapplication A,Betc.
Upgrading
2.1to2.2 2.0to2.1
BasicInstructions
Theseinstructionsassumethatyouhavenoteditedyoursystemfolderinanyway.Ifyouhavethen
2.1to2.2Upgrading
Configuration
preloadinconfig.phphasbeenremoved.Youmustnowmanuallyinstancethe librariesyouwanttouse.
Libraries
2.0to2.1Upgrading
Thereareanumberofchangestothemain'index.php'fileandthe'config.php'system file.Thequickestwaytoupgradeismakeabackupofyour'index.php'andyourapplication 'config.php'file.Callthebackupsfile_name_version.of.Kohana.e.g.index.php_2.0. Youcouldconsidernamingyoursystemfolderwiththeversionnumber:'system_2.1.1'rather thancopyingthenewoneoverthetop.Youcanthensimplyreverttoapreviousversionifthereare anyissues. Installthenew'index.php'and'application/config.php'files,andupdateanyvalues inthemtoreflectthechangesyoumadeinyouroriginalfiles.The'$kohana_system'should pointtothenewversionedsystemfolder. Thencontinuewiththechangesinotherfiles(ifneeded)statedbelow. Thismethodismorereliablethanmakingincrementalchangestoexistingfilesbasedonalistand youcansimpleswapbacktotheoldversionifthingsgowrong.
Configuration
show_errorshasbeenremoved.
Helpers
Validation
trim,md5,sha1Validationrulesmustnowbeprecededby=(e.g.'=trim'). Validationrule'regex'mustnowspecifythedelimiter.
Database
Deprecatedstuff
Troubleshooting
Programmingisart?Soisdebugging!AfewtipstokeepyourcodebugfreeandhowKohanacan help.
Can'tfigurethingsoutonyourown?
DeployingKohanatoProduction:
HereareafewitemsyoushouldkeepinmindbeforedeployingyourKohanaapplicationtoa
productionenvironment.
1.Removethevariousdemoandexamplecontrollers
Kohanabundlesavariousdemosandexamplecontrollerstohelpuserswhengettingstarted.Here areafewthatshouldberemoved:
2.Modifyyourconfigurationfiles
Kohanaprovidesvariousdefaultconfigurationfilesinthesystem/configdirectory.Since Kohanautilizesacascadingfilesystem,youhavetheoptiontoeitherutilizethedefault configurationfileversionsoroverridethesefileswithyourowncustomversionsbycreatingacopy intheapplication/configdirectory. Modifyyourapplication/config.php:
change$config['site_domain']fromyourdevelopmentsettingtotheproduction domain. set$config['display_errors'] = FALSE;todisableerrormessagesfrombeing displayed.Youcanstillcheckerrormessagesinyourlogfile.Checkyoursettingsin config/log.phptobesure. system/config/routes.phpsetyour$config['_default']toyourdefault controller system/config/encryption.phpchangethedefault$config['key'] modules/auth/config/auth.phpchangethedefaultsaltoffsetsin $config['salt_pattern'](ifyouusetheAuthmodule) system/config/cookie.phpsetyour$config['domain'] system/config/session.phpsetorverify$config['driver'], $config['name'],$config['encryption'],$config['expiration'] system/config/database.phpconfigureyourcustomdatabaseconnections(if required) system/config/log.phpsetyour$config['threshold'] = 1;.Thissets yourlogthresholdtoasuitablelevelforproduction.Higherthresholdlevelswilllogless criticalnoticesandinformation,butcanslowdownyourapplication.
Youshouldalwaystrytocreatecustomversionsofthefollowingfiles:
Youshouldalsoconsidercreatingcustomversionsofthefollowingfiles:
3.MoveKohanacoredirectoriesoutsideofthedocumentroot
Ifyourhostdoesnotallowthisstructure,usean.htaccessfiletoprotectthecoredirectories. AlthoughthisisanoptionalstepandnotrequiredbyKohana,itisconsideredagoodsecurity practicetoplaceasfewfilesaspossibleinyourpublicwebserverdocumentrootdirectory.Since mostwebhostsgiveyouaccesstoatleastonelevelabovethewebserverdocumentroot,thisshould
notbeaproblem. MovingyourcoreKohanadirectoriesalsogivesyoutheabilitytoutilizeonecentralKohana codebaseonyourserverthatcanbesharedbymultiplewebsites.Youcouldalsocreateasetof commonmodulesusedacrossallofyourwebsites. ToaccomplishthisinKohana,dothefollowing: 1. moveyourKohanasystem,application,andmodulesdirectoriesatleastonelevel aboveyourdocumentrootdirectory(typicallypublic_htmlorwww). 2. modifythefollowinglinesinyourindex.phpfile: $kohana_application = '../application'; $kohana_modules = '../modules'; $kohana_system = '../system'; Note:Thisexampleassumesonelevelabovepublic_html,however,youcanuserelativeor absolutedirectorieswhenspecifyingdirectorylocations. Yourfinaldirectorystructurewilllooksimilartothis:
yourdomain_root_directory +- application +- system +- modules +- public_html (web server document root) | - index.php | - .htaccess
Removingindex.phpFromURLs
Removingtheindex.phpfromyourwebsiteURLslookbetter,andcanhelpwithSEO. Note:ThistutorialonlyfocusesonApache,butcanbeadaptedforotherHTTPservers. .htaccess Weshouldstartoutbyremindingyouthatinprogrammingandcomputingthereisalwaysmorethan onewaytoaccomplishthesamejob.Thesamegoesforthisparticulartaskand,asisalwaysthe case,eachhasitsownprosandcons.Let'slookatafewtohelpyoudecidewhichisbestforyour situation. First,youwillneedtocreatea.htaccessdocumenttoenableURLrewriting: # Turn on URL rewriting RewriteEngine On # Put your installation directory here: # If your URL is www.example.com/, use / # If your URL is www.example.com/kohana/, use /kohana/ RewriteBase / # Do not enable rewriting for files or directories that exist RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # For reuests that are not actual files or directories,
# Rewrite to index.php/URL RewriteRule ^(.*)$ index.php/$1 [PT,L] Thisexampleisquitedynamicinthatyoucanaddfilesanddirectoriestoyourdocumentrootasyou desireandyou'llneverneedtomodifytherewriterules.Anyfilesanddirectoriesthatexistunder yourdocumentrootwillbeserved.Ifarequestismadeforanonexistantfileordirectory(whichis reallywhattheindex.phplessKohanaURLsare),therequestisrewrittentoberoutedthrough index.phptransparently.IfitcanberoutedbyKohana,thepageisserved.Finally,ifitwasn'ta requestforanexistingfileordirectoryandcouldnotberoutedbyKohana,aKohanaerrorpage(ex: 404)isdisplayed.Soyounotonlyhavedynamicrewriterules,butyougetconsistencyinyourerror pagessitewide. However,thisapproachdoesnotprotectyourmoresensitiveanunintendedPHPfilesagainstaccess. Sosomeonecouldenter,forexample,http://www.example.com/application/views/ andgetalistofallyourviewfiles.Ideally,youshouldneverhaveyoursystemorapplication directories,oranyotherfilesyoudonotwantaccessed,underyourdocumentroot.Butsomeservers aresetupsuchthatyouraccesstotheserverisrestrictedtodocumentrootandyouhavenochoice. Read"Movingsystemandapplicationdirectoryoutofwebroot"at http://doc.kohanaphp.com/installationtolearnhowtomovesystem/andapplication/outof yourdocumentroot.Ifyoufindthatyoudonothaveproperaccessonyourservertochangeyour filesystemsetup,continueoninthistutorialforotheroptions. .htaccess Let'sprotectagainstdirectaccesstothesefiles: # Turn on URL rewriting RewriteEngine On # Put your installation directory here: # If your URL is www.example.com/kohana/, use /kohana/ # If your URL is www.example.com/, use / RewriteBase /kohana/ # Protect application and system files from being viewed RewriteCond $1 ^(application|system) # Rewrite to index.php/access_denied/URL RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L] # Do not enable rewriting for other files that exist RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Rewrite to index.php/URL RewriteRule ^(.*)$ index.php/$1 [PT,L] controllers/access_denied.php BecausewearerewritingtheURLtoindex.php/access_denied/,wewillneeda ControllertohandletheseURLs.Let'screateonenow:
<?php class Access_denied_Controller extends Controller { function _remap() { // Attempted access path, with "access_denied/" removed $path = preg_replace('|^access_denied/|', '', $this->uri->string()); // Display an error page throw new Kohana_User_Exception ( 'Direct Access Denied', 'The file or directory you are attempting to access, <tt>'.$path.'</tt>, cannot be accessed directly. '. 'You may return to the '.html::anchor('', 'home page').' at any time.' ); } } Now,whenauserattemptstoaccessanyfileordirectoryinsideofapplication/orsystem/, anerrorpagewillbedisplayed. Nowwehaveagood,workingsolutionthatkeepsindex.phpourofourURL,andprevents accesstoprotectedfiles.However,wecanstillmakethismoresecure,byonlyallowingspecific filestobedisplayed,andrewritingeverythingelse. .htaccess # Turn on URL rewriting RewriteEngine On # Put your installation directory here: # If your URL is www.example.com/kohana/, use /kohana/ # If your URL is www.example.com/, use / RewriteBase /kohana/ # Protect application and system files from being viewed RewriteCond $1 ^(application|system) # Rewrite to index.php/access_denied/URL RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L] # # # # # Allow these directories and files to be displayed directly: - index.php (DO NOT FORGET THIS!) - robots.txt - favicon.ico - Any file inside of the images/, js/, or css/ directories
RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|images|js| css) # No rewriting RewriteRule ^(.*)$ - [PT,L] # Rewrite all other URLs to index.php/URL RewriteRule ^(.*)$ index.php/$1 [PT,L] Nowwearereallydone.Youcanchangetheallowedfilesanddirectoriestowhateveryourown, specificneedsare. Note:Don'tfeellikeyouhavetousethemostsecuresolution,oranyofthesesolutions.Choosethe .htaccessfilethatbestsuitsyourneeds.Eachoftheexamplesherewillworkbetterforsome situationsthanothers.Ifyouwantmoreinformationaboutmod_rewrite,checktheApache Documentation.
Migration
UsersofKohanaversion1.x(Blueflame)orCodeIgniter1.xmigratingtoKohana2.0canfollow thesestepstomigratetheirapplication.
Installation
StartingwithafreshKohanainstall,deleteapplicationfolder,andcopyyourexisting applicationfoldertothesamelocation.
Configuration
Removeyouroldconfigfolder. 1. Copytheapplication/configdirectoryfromKohana2.xto application/config 2. Editapplication/config/config.php,themainconfigurationfilesforyour application 3. ReviewtheUserGuide:Configurationpage
Logging
Thelogsdirectoryneedstobewritablebythewebserveroryoucanturnloggingoff.
ClassNames
Renameallyourcontrollersto{NAME}_Controller.Forexample,ifyouroldcontrollerwas Page,makeitPage_Controller. MakeyourControllercontructorsPHP5ifneeded: 1. function __construct()insteadoffunction Page() 2. parent::__construct()insteadofparent::Controller()
Libraries
BaseControllers
Ifyouhaveabasecontrollerforyourapplication(inthelibrariesfolder)yourwillneedto: 1. ChangetheMY_Controller extends ControllertoController extends Controller_Core 2. ChangereferencestoMY_ControllerinyourcontrollerstoController 3. UsethePHP5syntaxfortheconstructorinyourbasecontroller
URI
TheCIfunctionuri_to_assoc($offset)becomessegment_array($offset, $associative)with$associativesettoTRUE.
Other
Classnamesneedtohave_Coreappendedtothemandbecapitalized.Thefilenamesshouldalso havethesamecapsastheclassname(withoutthecore). Referencestothoseclassesneedtobecapitalizedtomatchthelibrarycalls(withoutthecore). $thisloadisdeprecated.Kohanausesautoloadingsoyoucaninstantiateanobject(e.g.new View())withoutincludingtheclassfirst.
Helpers
Changeallyourhelpercallstothenewsyntax:helper::function() 1. 2. 3. 4. Example:html::anchor()insteadofanchor() Example:url::baseinsteadofbase_url() Example:form::open()insteadofform_open() Thedefaulthelpersareavailableinsystem/helpers
Ifyouhavecustomhelperstheyneedtobechanged.Assumingyourhelperfileisfoo.php: 1. wrapallthefunctionsinthefileinclass foo { } 2. prependpublic staticinfrontofallthefunctionnames Callsarenowmadeviafoo::function(). NotealsothattheCodeIgniterhelpersandlibrariestypicallyhavethislineatthetopofthescript: <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); ThisisnotvalidforKohanasoifyouhavecopiedthislineforyourownhelpersetcyouneedto
Views
Viewsarenowtreatedsomewhatdifferently.Insteadofbeingflatfiles,viewsarenowobjects. Thisallowsmuchgreaterflexibility,andeasierviewinviewhandling.
// Load the view and set the $title variable $view = new View('template', array('title' => 'User Details')); // Sets the $username variable in the view $view->username = 'JohnDoe'; // Sets the $visits variable to another view $view->visits = new View('user/visits', array('user_id' => 3)); // Renders the view to a string $str_view = $view->render(); // Displays the view $view->render(TRUE);
Note:UsingprintorechoonaViewwillcauseittorenderintoastring.Thisisveryusefulin Views:
<!-- This example is the "template" view from above --> <h1><?php echo $title ?> for <?php echo $username ?></h1> <div id="visits"><?php echo $visits ?></div>
Intheaboveexample,aViewobject,$visits,wasusedasastring.Thissyntaxisencouraged becauseitisveryshortandreadablewhenmixedwithHTML.
Models
Thereisaimportantnote,inCIyoucanusethe$thisinthemodelandyouhavethesamelibraries asyourcontroller,inkohanaonlythedblibraryisloadedonamodel.Ifyouneedmorelibrariesyou havetwooptions:
// Create a new object with the library $uri = new Uri; $value = $uri->segment(3); // Can not use $this->uri->segment(3) as used in CI // Use the instance of your controller $value = Kohana::instance()->uri->segment(3);
Reference
General
KohanaFilesystem
Filetypes
StrictlyfromKohana'sinterpretationofMVCLh(MVCLibrarieshelpers):
Modelsareusedtorepresentaspecificpieceofdata,suchasadatabaserowinaspecific table,oranHTMLform. ViewsasusedasdatatoHTMLrenderinglayers. Controllersareusedastheentrypoint,andhandlehowaURIisconvertedintoan application. Librariesareusedforasatoolthatoperateonsomeformofpreexistingdata,eitherinthe formofanarray(e.g.,Session,Validation,Input)orsomeotherdatastructure,suchasORM (databasetable)orArchive(filesystem). Helpersareusedforsimple,repetitivetasks,suchascreatingHTMLtags,makingaURI intoaURL,orvalidatinganemailaddress. Configurationfiles,simplestaticarraysthatareaccessedbyconvention(file.key) Language(i18n)files,accessthesameasconfig(file.key) Hooks,whichcanbeusedtohookintoKohanaduringveryearlyprocesses
Inaddition,Kohanaaddsthefollowingsupportingstructure:
TheBasics
FirstofallyoushouldgetacquaintedwiththedirectorystructureofadefaultKohanainstallation. Onceyouhaveunpackedityouwillseethis(note:thecontentsofyourmodulesdirectorywillvary accordingtotheoptionsyouselectonthedownloadpage):
root +- application | +- cache | +- config | +- controllers | +- helpers | +- hooks | +- libraries | +- logs | +- models | +- views | +- modules | +- media | +- config | +- controllers | +- helpers | +- libraries | +- ..... +- system | +- config | +- controllers | +- core | +- helpers | +- i18n | +- libraries
Youwillnoticethatalotofthedirectoriesintheapplicationandsystemdirectoriesare exactlythesame.ThisisbecauseKohanahasacascadingfilesystem.
Cascading
TheKohanafilesystemismadeupofasingledirectorystructurethatismirroredinalldirectories alongwhatwecalltheincludepath,whichgoesasfollows:
application > modules > system
Modular
TheKohanafilesystemisalsomodular.Thismeansthatcustomdirectoriescanbeinsertedalong theincludepathtobescannedwhenafileissearchedfor. SeeModulesonhowtosettheseup. Theapplicationandsystemdirectoriescanbethoughtofashardcodedmodules.Theyare treatednodifferentlyfromregularmodulesapartfromtheexceptionslistedbelow.
Exceptions
Thereare2mainexceptionsinthefilesystem: config.phpMUSTresideintheapplication/configdirectory.Itwillnotbereadifit existswithinamoduleorthesystemdirectory.Thereasonforthisisthatitcontainsthe modulessettingwhichmustbereadbeforeallotherssotheframeworkknowswheretherestof theconfigfilesarealongtheincludepath. Thecorefilesaspartofsystem/corearealsonotcascading.Theyarehardcodedintothe Kohanastartupproceduresandwillnotbeoverriddenbyfileshigheruptheincludepath.
Configurationandi18nFiles
Thesefilesarespecialastheircontententriesaremergedwhenmultiplefilesofthesamenameare foundalongtheincludepath.Entriesinfilesgreateruptheorderstilloverridethoseofwhicharein fileslowerdown.
SeeConfigurationandInternationalizationformoreinformationonthis.
Builtindirectories
cache
Bydefault,theCachelibraryusesthisdirectorytostoreitscacheswhenusingtheFiledriver.It shouldalsobewhereyoustoreanycustomcacheddatafromyourapplication.
config
AllconfigurationfilesthatarereadbytheConfigclassmustbestoredhere.
controllers
Allcontrollerstobedirectedtobytheroutermustgoinhere.
helpers
SeeHelpers.
hooks
SeeHooks.
i18n
LanguagefilesreadbyKohana::lang()arestoredhere.Theyaresplitupintosubdirectoriesusing thecountrycodeandlocaleasthename.SeeInternationalization.
libraries
SeeLibraries.
logs
Bydefault,logfilesgeneratedbytheLogclassarestoredintheapplication/logsdirectory.
models
SeeModels.
vendor
3rdpartylibrariesandscriptsthatarenotintegratedintoKohanashouldbestoredhere.See Librariesformoreinformation.
views
SeeViews.
Configuration
Informationonretrievingandsettingconfigurationitemscanbefoundontheconfigpage.
Structureofconfigfiles
Configurationfilescontainanarraynamed$config.Keysofthisarrayaretheactualconfiguration itemse.g. Example
$config['site_domain'] = 'localhost/';
Filestructureofconfigfiles
ThefilestructureofconfigfilesfollowsKohana'sfilestructure.
application > modules > system
config.php
Config.phpishardcodedintoKohana,meaningithastobeintheapplication/config directory.
/* * Options: * site_domain * site_protocol * index_page rewriting * url_suffix * allow_config_set * global_xss_filtering input * render_stats output * extension_prefix * modules * autoload */ - domain and installation directory - protocol used to access the site, usually HTTP - name of the front controller, can be removed with URL - an extension that will be added to all generated URLs - enable or disable setting of Config items - enable or disable XSS attack filtering on all user - render the statistics information in the final page - filename prefix for library extensions - extra Kohana resource paths, see <Kohana.find_file> - libraries and models to be loaded with the controller
Configurationfiles
cache.php Setsthecachedriver,cachelifetimeandgarbagecollection.SeeformoreinformationtheCache library.
cookie.php Setsdefaultsforcookies.SeeformoreinformationtheCookiehelper. database.php Setsdatabaseconnectionsettings.Multipleconfigurationsarepossbile.Seethedatabase configurationpage. hooks.php Enableordisablehooks.SeeHookspage. locale.php Setsthelocaleandtimezoneofanapplication.SeeInternationalizationpage. log.php Setstheloggingthreshold.SeetheLogpage. mimes.php Setstheavailablemimetypes.(Seethevalidation/uploadpage?) pagination.php Setspaginationsettings.SeethePaginationpage. payment.php Setspaymentsettings. profiler.php Setstheinformationtheprofilershouldshow.SeetheProfilerpage. routes.php SetstheroutesKohanashoulduse.Includes_defaultand_allowed.SeeRouting session.php Setssessionsettingsincludingthesessiondriver.SeeSession. upload.php Setsuploaddirectory. user_agents.php Setsavailableuseragentsincludingrobotsandmobilebrowsers.SeeUserAgent
view.php Allowedfiletypes(deprecated?)
KohanaURLs
URLsinKohanaarecomposedofsegments.AtypicalsegmentedURLis http://localhost/control/action/arg1/arg2 Thesegmentscorrespond(inorder)toacontroller,acontrollermethod,andthemethodarguments. Example
http://localhost/index.php?/articles/edit/1/my-first-article // or the same URL with url rewriting on http://localhost/articles/edit/1/my-first-article
Whenyousegmentizethisurlitbecomes
Segments
Assaid,Kohanaurlscontainsegments.
Example
http://localhost/articles/edit/1/my-first-article
Containsthesegments
AURIclassandaURLhelperprovidemethodstomakeworkingwithaurleasier.Youcanretrieve segments,determinethecurrenturlsegment,andvariousotheroperations.
URLrewriting
Bydefault,Kohanaurlscontainindex.php.Thisdoesnotlookveryniceandalsoisnotoptimized forsearchengines.Seethedifferencebetweenthefollowingurls.
http://localhost/index.php?/articles/edit/1/my-first-article // or the same URL with url rewriting on http://localhost/articles/edit/1/my-first-article
ThelatterlooksnicerandisSEOproof. Thefollowingurlsmightbeofinterestwhensettingupsuchasystem:
http://kohanaphp.com/tutorials/remove_index.html http://forumarchive.kohanaphp.com/index.php/topic,246.0.html
Theyofferslightlydifferentsolutionsbuteachshouldworkequallygood.
Suffix
Kohanaallowsyoutosetasuffixtoyoururls. Example
http://localhost/index.php?/articles/edit/1/my-first-article.html
Settingthiscanbedoneintheapplication/config/config.phpfileunderurl_suffix
Allowedcharacters
Somecharactersarenotallowedinurls.Youcansettheallowedcharactersinthe config/routes.phpfile.Seeformoreinformationtheroutingpage.
QuerystringsandGETsupport
QuerystringsandGETsupportareenabledinKohana.Youcansimplyappendyoururlswith? var=valuetopassiton.ThekeysandvaluesareinspectedandcleansedbytheInputlibrarywhen global_xssison.
Routing
Typically,aURIwillmaptoacontrollerclassandmethodonaonetoonebasisandprovide argumentswherenecessary.Forexample,
http://www.example.com/class/function/arg1/arg2
Kohana'sroutingconfiguration
Inordertoalterroutingyouhavetohaveacopyofroutes.phpinyour application/configdirectory.Ifitisnotalreadytherecopytheonefromthe system/configdirectory. Thedefaultroutes.phpwillhavetwoentries:
$config['_allowed'] = '-a-z 0-9~%.,:_';
$config['_allowed']determineswhichcharactersareallowedinaURI.Whenchanging this,takecarenottoallowcharactersintheURIthatcouldcompromiseyourapplication.
$config['_default'] = 'welcome';
Specifyingyourownroutes
Inadditiontothedefaultrouteabove,youcanalsospecifyyourownroutes.Thebasicformatfora routingruleis:
$config['route'] = 'class/method';
andyouvisitedwww.example.com/testinawebbrowser,youwouldseethepageat www.example.com/foo/bar.
Usingregularexpressions
Theroutepartofaroutingruleisactuallyaregularexpression.Ifyouareunfamiliarwithregular expressionsyoucanreadmoreaboutthematthePHPwebsite.Usingregularexpressions,youcan bemoreselectiveaboutwhichURIswillmatchyourroutingrules,andyoucanmakeuseofthesub patternbackreferencingtechniquetoreusepartsoftheURIinit'sreplacement. Thisisbestdescribedwithanexample.SupposewewantedtomaketheURL www.example.com/article/22work,wemightusearoutingrulelikethis:
$config['article/([0-9]+)'] = 'news/show/$1';
Shortcuts
Inadditiontobeingabletouseregularexpressions,therearealsotwoshortcutsprovided.Theyare:
:anymatchesanynonblankstringofcharacters :nummatchesanynumber
whichlooksmuchneater.
Examples
Loadingresources
SinceKohana2.1.2$thisload()isdeprecated
Autoloading
PHPhasfunctionalitytoautomaticallyloadfilesifacertainclasshasnotbeenloadedyet.Kohana employsthisfunctionality. Example
$user = new User_Model; $cache = new Cache(); html::stylesheet(); $this->layout = new View('layout');
Loadinglibraries
Librariescanbeloadedingeneralintwodifferentways.Forexampleloadingthesessionlibrary:
$this->load->library('session'); // the object can be approached with $this->session e.g. echo $this->session->id() // this is the CodeIgniter compatible approach // another possiblity using $session = new Session; echo $session->id(); PHP5's nifty auto_load function
Loadingdatabase
Apartfromtheaforementionedmethodsloadingthedatabasecanalsobedonelikethis
$this->load->database();
Note:inmodelsthedatabaseisloadedautomatically.
Loadinghelpers
Note: Loadingahelperusing$thisloadhelper()isdeprecated,itwon'tworkandwill triggeradebugerrorinthelog. Usingahelperisfairlysimple.Justcallmethodasastaticmethod.Theclasswillbeloaded automatically
echo url::base();
Loadingviews
ViewsarethefinaloutputofKohana.Theycanbeembeddedintoeachothersoastohelpyouin makingyoursite.Thereismorethanonesyntaxtoloadaview.Theactualrenderingofaviewis notdonewhenyouloadone.MoreonviewscanbefoundontheviewspageInformationonthe viewclasscanbefoundontheviewclasspage. Example
$this->layout=new View('layouts/layout'); // will load the file views/layouts/layout.php //alternate syntax $this->layout=$this->load->view('layouts/layout'); //will render the view $this->layout->render(TRUE);
Loadingmodels
Toloadamodelthereismorethanonemethod.Thesearethebasicmethods,morecanbefoundon theModelspage.
ForinstanceyourmodelisUser_Model,thefilenamewouldbemodels/user.phpTheloading ofthemodelhappensinthecontroller.Example
$user = new User_Model; $name = $user->get_user_name($id); //get_user_name is a method defined in User_Model // alternative syntax $this->load->model('user'); $name = $this->user->get_user_name($id);
Preloadingresources
ThisfunctionalityisdeprecatedandwillnolongerbeavailableinKohana2.2.Useabasecontroller instead. Intheapplication/config/config.phpyoucanconfigurewhichlibrariesormodelsshouldbe automaticallyloadedoneachpageload.
$config['preload'] = array ( 'libraries' => 'database, session', 'models' => 'book' )
Controllers
Controllersstandinbetweenthemodelsandtheviewsinanapplication.Theypassinformationon tothemodelwhendataneedstobechangedandtheyrequestinformationfromthemodel.For exampledatabaseinserts,updatesanddeletesfordatachangeanddatabaseselectsforinformation retrieval.Controllerspassontheinformationofthemodeltotheviews,theviewscontainthefinal outputfortheusers. Controllersarecalledbyanurl,seeformoreinformationUrlsformoreinformation.
Controllernamingandanatomy
Acontroller'sfilenamecanbebasicallyanything.Thenameofthecontrollerclassmustcorrespond tothefilename. Conventionsforacontroller
Asimplecontroller
Westartwithasimplecontroller.ItwillshowHelloWorldonthescreen. application/controllers/article.php
class Article_Controller extends Controller { public function index() { echo 'Hello World!'; } }
Nowifyouenterwww.yoursite.com/articleyoushouldsee
Hello World
That'sit,yourfirstcontroller.Youcanseeallconventionsareapplied.
Moreadvancedcontroller
Intheexampleabovetheindex()methodiscalledbythewww.yoursite.com/articleurl.Ifthesecond segmentoftheurlisempty,theindexmethodiscalled.Itwouldalsobecalledbythefollowingurl: www.yoursite.com/article/index Ifthesecondsegmentoftheurlisnotempty,itdetermineswhichmethodofthecontrolleriscalled. application/controllers/article.php
class Article_Controller extends Controller { public function index() { echo 'Hello World!'; } public function overview() { echo 'Article list goes here!'; }
Nowifyoucalltheurlwww.yoursite.com/article/overviewitwilldisplay
Article list goes here!
Controllerwitharguments
Saywewanttodisplayaspecificarticle,forexamplethearticlewiththetitlebeingyourarticle-titleandtheidofthearticleis1. Theurlwouldlooklikewww.yoursite.com/article/view/yourarticletitle/1Thelasttwosegments oftheurlarepassedontotheview()method. application/controllers/article.php
class Article_Controller extends Controller { public function index()
public function overview() { echo 'Article list goes here!'; } public function view($title,$id) { echo $id . ' - ' . $title; // you'd retrieve the article from the database here normally }
Whenyoucallwww.yoursite.com/article/view/yourarticletitle/1itwilldisplay
1 - your-article-title
Controllersandsubdirectories
Ifyouputacontrollerinasubdirectoryofthe/controllers/directory,Kohanawillincludethe subdirectoryinthemappingtothecontroller.E.g.afilein application/controllers/admin/user.phpwillcorrespondtotheurlhttp://localhost/ admin/user
Routingcontrollerselsewhere
IfforsomereasonthemappingfromtheURItothecontrollerandmethodisnotrightforyouyou canuseroutingtomapaURItoanothercontroller.E.g.havelocalhost/about/memapto http://localhost/articles/view/1 SeeRoutingformoreinformationonthis.
Specialmethods
index
index()isthemethodthatwillbecalledwhenthereisnoothermethodcall.E.g.ifyourcontroller iscalledWelcome_Controller,andthefollowingurliscalledhttp://example.com/welcome thentheindexmethodiscalled.
_remap
Ifyouhavethismethodinyoucontroller,thenallrequeststothecontrolleraresenttoit,bypassing thedefaultURItomethodmapping. Themethodispassedtwoparameterswhichcanbehandledasintheexamplebelow:
class Article_Controller extends Controller { public function _remap( $method, $data )
{ // method is the first part of the uri. // it'll be index if there is no segment following the controller name // or the segment if there is // the $data param is an array of the remaining uri segments (if any) // otherwise it is an empty array } }
Examples
www.domain.com/article
_default
_default()isthemethodcalledwhenamethodofacontrolleriscalledthatdoesn'texist.E.g.http:// example.com/welcome/sthrandom90923,themethodsthrandom90923doesn'texistsoifitexists _default()willbecalled.Thisishandyifyouwanttotriggera404forexample.
Privatemethods
Sometimesyouwantsomemethodsinyourcontrollerwhichshouldnotbeavailableonyour website.Theyareonlyusedinternally.Thiscanbedonebydeclaringmethodsprivateand/or prependingthemwith_ application/controllers/home.php
class Article_Controller extends Controller { public function index() { echo 'Hello World!'; }
Whenyoucallwww.yoursite.com/article/_article_formyou'llencountera404.
Classconstructors
Ifyoudeclareaconstructorinyourcontroller,forexampletoloadsomeresourcesfortheentire controller,youhavetocalltheparentconstructor. application/controllers/home.php
class Article_Controller extends Controller { protected $db; protected $session; public function __construct() { parent::__construct(); //this must be included $this->db = new Database; $this->session = new Session; } public function index() { $this->session->get('user_id'); } public function view($article_id) { $article_id = (int) $article_id; $article = $this->db->getwhere('articles', array('id' => $article_id)); } }
ThisexamplealsoshowshowyoucanretrieveanarticlefromthedatabaseusingURLsegments.If youcallwww.yoursite.com/article/view/5,itwillretrievethearticlewhoseidis5.
SpecialControllers
Usingabasecontrollerforyourapplication
Usingabasecontrollerforyourapplicationcanbeveryhelpful.Youcanexecutecodeonevery pageforexample,usefulforauthenticatingandauthorizingusersforexampleordoingsession magic. ExampleMY_Controller.php
<?php class Controller extends Controller_Core {
public function __construct() { parent::__construct(); // authentication goes here for example } public function do_something() { // method available in all controllers } }
Libraries
ThefollowingKohanalibrariesareloadedautomaticallybytheframeworkandshouldalwaysbe availabletoyou:
OtherlibrariescanbeloadedautomaticallybyKohanawhentheyareused.Forexample,toloadand usetheProfilerlibrary,youcanjustaddthefollowinglinetoyourcontroller'sconstructor:
$this->profiler = new Profiler;
Alternatively,ifyouwishtoloadlibrariesmanually,youcandothefollowing:
$this->load->library('some_library');
Note:usingtheabovemanualmethodofloadinglibrariesisdeprecatedsinceKohana2.1.2. Formoreinformation,seethepageonLoading.
Addingyourownlibraries
Whencreatingyourownlibraries,thesearetheconventionsthataresuggested:
Forexample,letssupposethatyouwantedtocreateanewbooklibrary.Youmightcreatethe followingfile:
File:application/libraries/Book.php
<?php defined('SYSPATH') or die('No direct script access.'); class Book_Core { // add constructor/methods/properties here } ?>
Extendinglibraries
Kohanaalsoallowsyoutoextendedit'sbuiltinlibrariessothatyoucanaddyourownfunctionality tothem,orchangethewaytheywork.Youshouldneverchangethefilesin system/libraries.Insteadyoucancreateanewlibrarythatextendsabuiltinlibrary. Youcanalsoextendyourownlibraries,solongasyouhaveadded_Coretotheendoftheir classnames. Whenextendingalibrary,theconventionsarethesameasforwhenyouarecreatinganewlibrary, withacoupleofexceptions:
ReplacingKohana'sbuiltinlibraries
Itisalsopossible(althoughprobablylessoftenrequired)toreplacingoneofKohana'sbuiltin librariesentirely.Theconventionsarethesameaswhenyouareaddingyourownlibrary,withone exception:
Appending_Coretotheclassnameisnotoptionalyoumustdoit!
If,forexample,youwanttoreplacetheProfilerlibrary,youmightcreatethefollowingfile: File:application/libraries/Profiler.php
<?php defined('SYSPATH') or die('No direct script access.'); class Profiler_Core { // define your own profiler here } ?>
3rdpartylibraries
Ifyoushouldrequire3rdpartylibraries(suchasSimplepie,ZendFramework,orPearlibraries)you canplacetheseintheapplication/vendorsdirectory.LoadingthemfromKohanaissimple. Youmightdothefollowing:
Kohana::find_file('vendors','some_class')
ToincludeaZendFrameworkcomponent,youmightdothefollowing:
// example
NotethatitalsocanbeplacedintheSYSPATHfolderbutitthenmightbeoverwrittenbyanew versionofKohana.Modulefolderswilldoaswell.Inthiscaseuse
ini_set('include_path',ini_get('include_path').PATH_SEPARATOR.SYSPATH.'vendor/ze nd/library/');
Helpers
Helpersaresimplyhandyfunctionsthathelpyouwithdevelopment. Helpersaresimilartolibrarymethods,butthereisasubtledifference.Withalibrary,youhaveto createaninstanceofthelibrary'sclasstouseitsmethods.Helpersaredeclaredasstaticmethodsof aclass,sothereisnoneedtoinstantiatetheclass.Youcanthinkofthemasglobalfunctions. Aswithlibraries,thehelperclassesareautomaticallyloadedbytheframeworkwhentheyareused, sothereisnoneedtoloadthemyourself. Hereisanexamplecalltoahelper:
// show the location of this Kohana installation echo url::base();
AswithmostofKohana,youcanaddyourownhelpersandreplaceorextendKohana'sbuiltin ones.
Addingyourownhelpers
Whencreatingyourownhelpers,thesearetheconventionsthataresuggested:
?>
andthentouseyourhelper,youwoulddothefollowing:
javascript::alert("Oh no!");
Extendinghelpers
Kohanaalsoallowsyoutoextendeditsbuiltinhelperssothatyoucanaddyourownfunctionalityto them.Youshouldneverchangethefilesinsystem/helpers!Instead,youcancreateanew helperthatextendsabuiltinhelper. Youcanalsoextendyourownhelpers,solongasyouhaveadded_Coretotheendoftheirclass names. Whenextendingahelper,theconventionsarethesameasforwhenyouarecreatinganewhelper, withacoupleofexceptions:
ExtendingthecoreclassesisnotonlyallowedinKohana,butisexpected.
ReplacingKohana'sbuiltinhelpers
Itisalsopossible(althoughprobablylessoftenrequired)toreplacingoneofKohana'sbuiltin helpersentirely.Theconventionsarethesameaswhenyouareaddingyourownhelper,withone exception:
Appending_Coretotheclassnameisnotoptionalyoumustdoit!
If,forexample,youwanttoreplacetheurlhelper,youmightdosomethinglike: File:application/helpers/url.php
<?php defined('SYSPATH') or die('No direct script access.'); class url_Core { // define your own url helper here
} ?>
Views
SeeViewclassformoreindepthinformationonusingviewsinyourcode.
Overview
Viewsarefilesthatcontainthedisplayinformationforyourapplication.Thisismostcommonly HTML,CSSandJavaScriptbutcanbeanythingyourequiresuchasXMLorJsonforAJAXoutput. Thepurposeofviewsistokeepthisinformationseparatefromyourapplicationlogicforeasy reusabilityandcleanercode. Whilethisistrue,viewsthemselvescancontaincodeusedfordisplayingthedatayoupassinto them.Forexample,loopingthroughanarrayofproductinformationanddisplayeachoneonanew tablerow.ViewsarestillPHPfilessoyoucanuseanycodeyounormallywould.Viewsare executedintheControllernamespacesoyouhaveaccesstoallresourcesyouhaveloadedinto $this WhenthisviewisrendereditisexecutedjustasanyPHPscriptwouldandtheoutputfromitis returned(orsenttothebrowserifyousowish).
Creatingviews
Viewsneedtobeplacedintheviewsdirectory.Thefilenameminustheextensionbecomesthe view'sname.Viewscanbearrangedinsubdirectoriesifneededbutthepathmustbespecified whenloadingthem. Examples
// Filename home.php $view = new View('home'); // Filename list.php in sub-directory 'products' $view = new View('products/list');
Loadingviews
Thereare3waystoloadaview.Itisimportanttonotethatthissimplycreatesaninstanceofthe Viewclass,atthispointtheviewfilehasnotbeenreadandnooutputiscreated.Thisonlyhappens whenitisrendered.
Newobject
Createanewinstanceoftheclass.
$view = new View('welcome');
Factory
Usethefactory()staticmethod.Thisisessentiallythesameascreatinganewobjectexceptitis immediatelyreturnedsomethodchainingispossible.
$view = View::factory('welcome');
Loader
SinceKohana2.1.2loaderisdeprecated. Usethebuiltinloader.Usingthefactorymethodispreferredoverthisasitdoestheexactsame thingbutfactoryisshorterandclearer.Theloadermethodismainlyprovidedforeasiermigration fromCodeIgniter.
$view = $this->load->view('welcome');
Passingdataintoyourviews
Dataispassedfromthecontrollertotheviewbywayofananobject. Let'slookattheController:
class Welcome_Controller extends Controller { function index() { // Load the view as an object $view = new View('yourview'); // Adding variables to the object that will be displayed in the view $view->title = "Welcome to Kohana !"; $view->heading = "My Heading"; $view->content = "My content here."; // Render the view $view->render(TRUE); } }
Nowopenyourviewfileandaddvariables:
<html> <head> <title><?php echo $title;?></title> </head> <body> <h1><?php echo $heading;?></h1> <p><?php echo $content;?></p> </body> </html>
Viewswithinviews
Toloadviewswithinotherviews:
// Example of code inside your Controller $view = new View('template'); $view->header = new View('header'); $view->content = new View('content'); $view->footer = new View('footer'); $view->header->title = 'Title of page'; // string for variable $title in view header.php $view->content->heading = 'Heading of your page'; // string for variable $heading in view content.php $view->footer->copyright = 'Copyright'; // string for variable $heading in view footer.php $view->render(TRUE);
View:template.php
<?php echo $header; ?> <?php echo $content; ?> <?php echo $footer; ?>
View:header.php
<html> <head> <title><?php echo $title; ?></title> </head>
View:content.php
<body> <h1><?php echo $heading; ?></h1>
View:footer.php
<?php echo $copyright; ?> </body> </html>
Output:
<html> <head> <title>Title of page</title> </head> <body> <h1>Heading of your page</h1> Copyright </body> </html>
footer.phpintoonefile.
Datascope Rendering
Executetherendermethodontheviewinstance. Examples Ex1:RenderonViewinstance
$view = new View('sample'); $view->render(TRUE);
Ex2:RenderonView::factory
View::factory('sample')->render(TRUE);
CompleteExample
Controller:products.php
$products = array( array( 'name' => 'Product1', 'quantity' => '3' ), array( 'name' => 'Product2', 'quantity' => '7' ) ); $view = new View('products/list'); $view->title = 'Products'; $view->set('products', $products); $view->render(TRUE);
Models
Whataremodels?
Modelsareclassesdesignedtoworkwithinformationgivenbyoraskedforbythecontroller.For example,youhaveaguestbook,thecontrollerwillaskthemodeltoretrievethelasttenentries,the modelreturnsthoseentriestothecontrollerwhopassesthemontoaview.Thecontrollermight alsosendnewentriestothemodel,updateexistingonesorevendeletesome. NotethatKohanadoesn'tforceyoutousemodels.Ifyouchoosenottousethem,youarefreetodo so.
Namingmodels
Kohanausesspecificrulesforthenamingofmodels.Theseare:
Example Supposethatyouhaveatableinthedatabasecalledusers(whichisapluralname).Themodel
Loadingmodels
ThegenerallyacceptedwayofloadingaModelinKohanaistodosowithinyourController. Forinstance,toloadtheusermodel(above)fromapplication/models/user.phpaddthe followingtoyourcontroller:
$user = new User_Model; $name = $user->get_user_name($id); User_Model // get_user_name is a method defined in
YoucanthenaccesstheusermodelfromanycontrollerthatextendstheTemplate_Controller,like this:
$name = $user->get_user_name($id); User_Model // get_user_name is a method defined in
Usage
Amodelmightlooksomethinglikethis:
class User_Model extends Model {
public function __construct($id = NULL) { // load database library into $this->db (can be omitted if not required) parent::__construct($id); } /** * Get information about a user, given their user_id * @param integer the user_id * @return the result object */ public function get_user($user_id) { $this->db->where('user_id', $user_id); return $this->db->get('users'); } /** * Add a new user. Assumes an auto incrementing user_id in the database. * @param array user data. E.g., * array( 'name' => 'test', 'email' => 'test@example.com' ) * @return void */ public function insert_user($data) { $this->db->insert('users', $data); } /** * Replace user details. * @param array user data. E.g., * array( 'name' => 'test', 'email' => 'test@example.com' ) * @return void */ public function update_user($user_id, $data) { $this->db->where('user_id', $user_id); $this->db->update('users', $data); } }
Note:Whenutilizingdatafromaformalwaysuse$thisinputpost('var_name', TRUE)toensuredataissanitizedbeforeusing.LearnmoreabouttheInputlibrary.
Usingadatabaseinyourmodel
Ifyourmodel'sconstructorcontainsthelineparent::__construct();,thedefaultdatabase functionalitywillbeloadedinto$thisdb.Youcanuseallofthedatabase'sfunctionswiththe $thisdbobject.
Usingamodelinyourcontroller
Usingtheexamplemodelabove,youcanintegratethismodelintoyourcontrollerasfollows: 1. Createaninstanceofthemodelinyourcontrollertomakeitaccessible.Thiscanbedone
directlyinacontrollermethodas$user = new User_Model.Ifyouwantthemodel accessiblefromallofyourcontrollermethods,createaninstanceofthemodelinyour controllerconstructor:$thisuser = new User_Model. 2. Ifyouusedtheconstructormethodabove,youcannowretrieveuserinformationfromyour databasewithinanyofyourcontrollermethodswith:$user = $thisuserget_user(1).The$uservariablenowcontainsadatabaseresultset object(fortheuserwithid=1)thatcanbepassedtoyourView. 3. Ifyoupassedtheentire$uservariabletoyourView,youcanaccessspecificuserdata elementswithinyourViewintheform$username.SeeDatabaseLibraryformore information.
ORM
Seeformoreinformation
ORM
Events
SeeEventforinformationonadding,running,removingandusingcustomevents. Kohanaeventsconsistofanameandcallback.Namesusuallyincludeaprefixwiththename1),but arenotrequiredto.Allofthecoreeventsareprefixedassystem.name.
SystemEvents
ThefollowingeventsaredefinedintheKohanacorefiles.Thepredefinedactionsfortheseevents areaddedinKohana::setup. system.ready Calledimmediatelyafterhooksareloaded.Thisistheearliestattachableevent.Nothingisattached tothiseventbydefault.Hooksareloadedbeforethispoint. system.routing ProcessestheURLanddoesrouting.CallsRouter::find_uriandRouter::setupbydefault. system.execute Controllerlocatingandinitialization.Acontrollerobjectwillbecreated,asaninstanceofKohana. CallsKohana::instancebydefault. system.post_routing Kohana2.2Triggeredafterallroutingisdonesointerventionsinroutingcanbedonehere.If
Router::$controllerisemptyafterthiseventa404istriggered. system.404 Calledwhenapagecannotbefound.CallsKohana::show_404bydefault. system.pre_controller Calledwithinsystem.execute,afterthecontrollerfileisloaded,butbeforeanobjectiscreated. system.post_controller_constructor Calledwithinsystem.execute,afterthecontrollerconstructorhasbeencalled.Kohana::instancewill returnthecontrolleratthispoint,andviewscanbeloaded.Controllermethodshavenotbeencalled yet. system.post_controller Calledwithinsystem.execute,afterthecontrollerobjectiscreated.Kohana::instancewillreturnthe controlleratthispoint,andviewscanbeloaded. system.send_headers Calledjustbeforetheglobaloutputbufferisclosed,beforeanycontentisdisplayed.Writing cookiesisnotpossibleafterthispoint,andSessiondatawillnotbesaved. system.display DisplaystheoutputthatKohanahasgenerated.Viewscanbeloaded,butheadershavealreadybeen sent.TherenderedoutputcanbemanipulatedasEvent::$data. system.shutdown Lasteventtorun,justbeforePHPstartstoshutdown.RunstheKohana::shutdownmethodby default.
Hooks
HooksareincludedearlyinKohanaandcanbeusedtoexecutecodebeforee.g.controllersare loadedsoyoucancheckforforexampleauthenticationearlyinKohana.Eventsandhooksgohand inhandsinceinhooksyoucanattachcodetoevents.SeeformoreinformationtheHookspage. 1)Anexampleofaprefixisprefix.name
Hooks
HooksarebasicallyfilesincludedatthestartofKohana,tobemorespecifictheyareloadedinthe Kohana::setup()method.Atthistimethesefilesareloaded,sotheirmethodscanbeused
Noeventhasbeenstartedyet,thefirsttobestartedissystem.ready Hookfilesshouldbeputinapplication/hooksorsimilarlyinamodulefolder.
Configuringhooks
Toconfigurehooksedit'hooks.phpinyourapplication/configdirectory.Ifthefileisnotthere copytheonefromsystem/config. Itwilllooksomethinglikethis: File:hooks.php
$config['enable'] = FALSE;
Hooksandevents
ThepowerofhooksmainlycomesfromtheEventsclass.Hooksareloadedbeforeanyoftheevents arestartedsoyoucanattachahooktoanevent.Forexampleyouloadthefollowingfileasahook Examplehooks/power.php
class Power { public function Kohana(){ Event::$data=Event::$data.'<!-- Powered by Kohana-->'; } } Event::add('system.display', array('Power', 'Kohana'));
Thiswilladdasmallnoticetothebottomofeachpage(<!PoweredbyKohana>).Itutilizesthe Event::$datatomanipulatethefinaloutput.
Constants
WhenusinghooksyoumightneedtogetunderthehoodofKohana.Whenthehooksareloaded
theseconstantsaresetinindex.php
ErrorHandling
Seeformoreinformation
Logclass explanationofthelogclass.
Config.display_errors
Intheindex.phpfilethereisasettingdisplay_errors.Thisdetermineswhethererrorsshouldbe outputtedtothescreenornot.Duringdevelopmentyou'dwanttosetthistoTRUE,butin productionsetthistoFALSEsoastopreventusersfromseeingerrors.Thiswon'taffectloggingof errors.
Exceptions
ExceptionsinKohanaarehandledbytheKohanaExceptionclasses.Therearethreetypesof exceptions:Kohana_Exception,Kohana_User_ExceptionandKohana_404_Exception.
Kohana_Exception
Kohana_ExceptionextendsException.TothrowaKohana_Exceptionani18n languagefilemustexist. Syntax
/** * @param string i18n language key for the message * @param array addition line parameters */ throw new Kohana_Exception(string $i18_lang_key [, string $message]);
Example
//... if($x == 0) throw new Kohana_Exception('math.division_by_zero'); // Throw a $lang['division_by_zero'] exception in ./i18n/en_US/math.php // "Cannot divide by zero." else if($x < 0) throw new Kohana_Exception('general.math.negative_number', $x); // Throw a $lang['math']['negative_number'] exception in ./i18n/en_US/general.php and pass the message $x // "The number passed was negative: -5" //...
Kohana_User_Exception
Kohana_User_ExceptionextendstheKohana_Exception.Thisissimilarto Kohana_Exceptionexceptthattheexceptionmessagesdonothavetobeinthei18nstructure. Syntax
/** * @param string exception title string * @param string exception message string * @param string custom error template */ throw new Kohana_User_Exception(string $title, string $message [, string $template]);
Example
//... if($x == 0) throw new Kohana_User_Exception('Cannot divide by zero', 'You passed a zero'); else if($x < 0) throw new Kohana_User_Exception('Number Type Exception', "Cannot use a negative number $x"); //...
Kohana_404_Exception
Kohana_404_ExceptionextendsKohana_Exception.Thisexceptionwilldisplaya404 errormessagetotheuser. Syntax
/** * @param string URL of page * @param string custom error template */ throw new Kohana_404_Exception([string $page [, string $template]]);
Example
//... if($x == 0) throw new Kohana_404_Exception('divide by zero'); // "The page you requested, Cannot divide by zero, could not be found." //...
Triggeringerrors Customerrorpages
Thesystem/views/kohana_error_page.phpisthedefaulterrorpage.Youcanoverload thisonebyhavingakohana_error_page.phpinyourapplication/viewsdirectoryor inasimilarmodulesdirectory.
Thedefaulterrorpagewillshowyoutheerroraswellasastacktraceifavailable.
Logging
Kohanacanlogerrors,debugmessagesandinformationalmessages.Thesettingcanbefoundin application/config/log.phpSeeformoreinformationonloggingtheLogclass.
Modules
Kohanaiseasilyextendableusingmodules.Modulesarereusablecollectionsofrelatedfilesthat togetheraddaparticularfunctionalitytoanapplication.Youmaywanttoreusesomehelpersor addauthenticationacrossmultipleapplications.Placeitinamodulefolderandyoucancopyitwith easeorhavemultipleapplicationsusethesamemoduledirectory. TheFilesystempageshouldbereadbeforethisonetounderstanditproperly.
Settingup
Itismostcommontohaveadirectorycalledmodulesinthesamedirectoryasthe applicationandsystemdirectories.Forinstance,wecreatedamoduleforACL(access controllists)andauthentication(auth)sincewewanttoreuseitacrossapplications.
root +- application +- system +- modules | +- acl | | +- helpers | | +- i18n | | +- libraries | | +- models | | +- vendor | | +- views | | | +- auth | +- helpers | +- i18n | +- libraries | +- models | +- vendor | +- views | +- index.php
Configuring
Onlyplacingmodulesinthemodulesdirectorywon'tloadthem,theymustbeconfiguredfor Kohanatousethem.Thiscanbedoneintheapplication/config/config.php file usingthe'modules'setting. Example
// Paths are relative to the docroot, but absolute paths are also possible $config['modules'] => array
( 'modules/acl', 'modules/auth', )
Internationalization
Internationalizationfilescanbefoundinthei18ndirectories.Thesedirectoriescanbefoundin system,applicationormodulesdirectories.Kohana'sowninternationalizationfilescanbefoundin thesystemdirectory. Inthei18ndirectoriesthedirectorieswiththelanguagefilescanbefound.Englishfilesarein en_US,Dutchinnl_NL,Germaninde_DEetc.
Localesetting
Theconfigurationfilelocale.phpsetswhichlocalewillbeused.Thefilecanbefoundinthe application/configdirectory,ifit'snottherecopytheonefromthesystem/configdirectory. Thefilewilllooksomewhatlikethis
$config['language'] = 'en_US'; $config['timezone'] = '';
Filestructure
root +- application | +- i18n | +- en_US | | +- coffee.php | | | +- de_DE | | +- coffee.php | | | +- zh_CN | | +- coffee.php | +- system | +- i18n | +- en_US | | +- cache.php | | | +- de_DE | | +- cache.php | | | +- zh_CN | | +- cache.php
Retrievinglanguagestrings
UsingKohana::lang()languagesstringscanberetrieved.Example
echo Kohana::lang('cache.resources'); //outputs is locale is set to en_US // Caching of resources is impossible, because resources cannot be serialized.
//If locale is set to de_DE // Das Cachen von Ressourcen ist nicht mglich, da diese nicht serialisiert werden knnen.
Settingyourownlanguagestrings
Itispossibletohaveyourownlanguagestringsinyourapplication/module.Simplyaddadirectory i18n,addthedirectoryofthelocaleandaddthefilewiththelanguagestrings.Forexample,you wanttohavelanguagestringsforcoffeeandstuffrelatedtocoffee.Namethefilecoffee.php andplaceitinapplication/i18n/en_US/ Formatofthefile
$lang = array ( 'cup' 'beans' 'java' language', ); => 'Coffee goes in here', => 'Coffee is created from beans.', => 'Place where coffee comes from, not the programming
Theselanguagestringscannowbecalledfromyourapplication Example
echo Kohana::lang('coffee.cup'); echo Kohana::lang('coffee.beans'); echo Kohana::lang('coffee.java');
Core
BenchmarkClass
Thebenchmarkclassallowsyoutotimeyourcode.Bydefaultseveralbenchmarksarerun:
Methods
start()
Benchmark::start($name)isusedtostartanewbenchmark.Supplyanuniquename. Returnsvoid.
Benchmark::start('benchmark1');
stop()
Benchmark::stop($name)isusedtostopabenchmark.Supplythenamegivenwhenthe benchmarkwasstarted.Returnsvoid.
Benchmark::stop('benchmark1');
get()
Benchmark::get($name, $decimals)isusedtoretrievetheresultsofabenchmark. Returnsanarraywiththeresults:timeisexpressedinseconds,memoryinbytes.
print_r(Benchmark::get('benchmark1')); // Output: Array ( [time] => 0.0078 [memory] => 472 )
The$decimalparameterisoptional.Itsdefaultvalueis4.
print_r(Benchmark::get('benchmark1', 6)); // Output: Array ( [time] => 0.007802 [memory] => 472 )
Ifyousetthe$nameparametertoTRUE,allbenchmarkswillbereturned.
print_r(Benchmark::get(TRUE, 3)); // Output: Array ( [477f51931a33e_total_execution] => Array ( [time] => 0.023
[memory] => 618940 ) [477f51931a33e_kohana_loading] => Array ( [time] => 0.012 [memory] => 369104 ) [477f51931a33e_environment_setup] => Array ( [time] => 0.002 [memory] => 54300 ) [477f51931a33e_system_initialization] => Array ( [time] => 0.003 [memory] => 65884 ) [477f51931a33e_controller_setup] => Array ( [time] => 0.008 [memory] => 177688 ) [477f51931a33e_controller_execution] => Array ( [time] => 0.000 [memory] => 4236 ) [benchmark1] => Array ( [time] => 0.008 [memory] => 472 ) )
ConfigClass
Providesmethodsforworkingwithconfigurationitems.
Wheretoputtheconfiguration?
Configurationfilesmustbeplacedinafoldernamedconfig,thisfoldercanresideinsystem, applicationoramodule.Applicationismoreimportantthansystemandwilloverrideit.Modules overridesystemfilesbutareoverriddenbyapplicationfiles. Theconfigfilemustbeinthisformat:
$config = array ( 'language' => 'en_US', 'timezone' => '' );
Methods
Retrievingconfigurationitems
Config::item($key, $slash = FALSE, $required = TRUE)retrievesa configurationitem,canreturnastring,arrayorboolean.$slashwillforceaforwardslashattheend oftheitem.$requireddetermineswhetheranitemisrequiredornot.
config::item('locale.language'); //returns the language from the **locale.php** file and returns the config['language'] item.
Settingaconfigurationitem
Forsettingconfigurationitemsinrealtimeyoumustenablethissettingintheconfig.phpfile. (core.allow_config_set) Config::set($key, $value)setsaconfigurationitem,returnsTRUEonsuccessorFALSE whenitdidn'tsucceed.
config::set('locale.language','nl_NL');
Note:
Ifyouwanttosetaconfigurationinrealtimemakesuretheconfig.allow_config_setissetto TRUEinapplication/config.php
Gettingtheincludepaths
Config::include_paths($process= FALSE)getstheincludepathsandreturnsanarray. Firstinthearrayistheapplicationpath,lastwillbethesystempath,otheritemswillbeinclude pathssetintheconfigurationitem'core.include_paths'.$process,iftrue,willreprocessthe include_paths.
config::include_paths();
Loadaconfigurationfile
Config::load($name, $required = TRUE)loadsaconfigurationfile.Config::item() loadsthemaswellifthey'renotalreadyloadedandretrievestheitemsstraightaway.
config::load('locale');
EventClass
Foranoverviewforaprogrammingoverviewofevents,pleaseseeEvent_handlerandEvent_loop. Kohanastoreseventsinqueues,asopposedtostacks.Thissimplymeansthat,bydefault,new eventswillbeprocessedafterexistingevents.
WhatisanEvent?
Kohanaeventsconsistofauniquenameandacallback.Bydefault,thereareseveraleventsdefined byKohana.Namesarecompletelyfreeform,buttheconventionistouseaprefix.nametomake eventnamesmoreunique.Allpredefinedeventsareprefixedassystem.name,eg: system.post_controller.
Methods
AllEventmethodsarestatic,andEventshouldneverbeinstanced.
add
Usedtoaddanewcallbacktoanevent.Iftheeventdoesnotalreadyexist,itwillbecreated.
// Calls the function "foo" after the controller method is executed Event::add('system.post_controller', 'foo'); // Calls the static method "Foo::bar" after the controller method is executed Event::add('system.post_controller', array('foo', 'bar')); // Calls the "bar" method in the "$foo" object when the output is rendered Event::add('system.display', array($foo, 'bar'));
Youcanalsocreateentirelyneweventsthisway:
add_before
Usedtoaddacallbackimmediatelybeforeanothercallbackinanevent.
// Add the function "faa" to be executed before "foo" Event::add_before('system.post_controller', 'foo', 'faa');
Iftheeventyouareinsertingbeforedoesnotexist,add_beforewillfunctionalexactlythesame asadd.
add_after
Usedtoaddacallbackimmediatelyafteranothercallbackinanevent.
// Add the function "fzz" to be after "foo" Event::add_after('system.post_controller', 'foo', 'fzz');
Iftheeventyouareinsertingafterdoesnotexist,add_afterwillfunctionalexactlythesameas add.
replace
Usedtoreplaceacallbackwithanothercallbackinanevent.
// Replace the "foo" function with the "oof" function Event::replace('system.post_controller', 'foo', 'oof');
Iftheeventyouarereplacingdoesnotexist,noeventwillbeadded.
get
Returnsofthecallbacksasasimplearray.
// Returns of the callbacks for system.post_controller $events = Event::get('system.post_controller'); // Loop through each event and call it foreach ($events as $event) { $return_value = call_user_func($event); }
Ifnoeventsexist,andemptyarraywillbereturned.Itisrecommendedtouseemptyifyouneedto validatethateventsexist.
clear
Clearoneorallcallbacksfromanevent.
// Clears the "oof" function from system.post_controller Event::clear('system.post_controller', 'oof');
Ifthismethodiscalledwithoutasecondargument,itwillcleartheentirequeueforthegivenevent.
run
Executeallofthecallbacksattachedtoanevent.
// Run the system.post_controller event Event::run('system.post_controller');
has_run
Checksifaneventhasalreadybeenrun.Thiscanisusefultomakeaneventrunonlyonce.
// Test if the event has already run if (Event::has_run('system.post_controller')) { echo 'post_controller has been run.'; } // Run the post controller event if it has not already been run Event::has_run('system.post_controller') or Event::run('system.post_controller');
Data
Event::dataisaspecialvariablethatcanbesetwhenusingEvent::run.Thedataisassignedby reference,andcanbemanipulatedbyallofthecallbacks.
// Debug the data echo Kohana::debug($data); // Run the post_controller event with data Event::run('system.post_controller', $data); // Display the changed data echo Kohana::debug($data);
Eventdataisclearedimmediatelyafterallofthecallbacksarerun,andcanonlybeaccessedduring callbackexecution.
KohanaClass
TheKohanaclassisatthecenterofKohana.ItloadsuptheRouter,dispatchestothecontrollerand doesthefinaloutput.
Characterset
Theclassalsosetsautf8header.Ifyouwantadifferentcharsetyoucanoverrideitbyplacingthis inforexampleyourcontroller.Thebrowserwillinterpretthepagewiththenewcharset.
header('Content-type: text/html; charset=iso-8859-1');
Methods
debug()
ReturnsHTMLformattedstringsofvariablesthatcanbeechotoscreennicely.
echo Kohana::debug($this->input->post());
PrintsoutthePOSTvariable
backtrace()
Willbecalledwhenanerroroccurs.Itdisplaysanoverviewoffilesandfunctionscalledsoyoucan spotthesourceoftheerror.Veryusefulfordebugging.
lang()
UsingKohana::lang()languagesstringscanberetrieved. Example
echo Kohana::lang('cache.resources'); //outputs is locale is set to en_US // Caching of resources is impossible, because resources cannot be serialized.
//If locale is set to de_DE // Das Cachen von Ressourcen ist nicht mglich, da diese nicht serialisiert werden knnen.
key_string()
Searchesforgivenkeyinanestedarray.Ittakes:
Example
$a = array ( 'levelone1' => array ( 'leveltwo1' => array ( 'a' => 'aaa', 'b' => 'aab', 'c' => 'aac' ), 'leveltwo2' => array
);
) ), 'levelone2' => array ( 'a' => 'ba', 'b' => 'bb', 'foo' => 'bar' )
Kohana::key_string('levelone1.leveltwo1.b', $a); //Returns 'aab' Kohana::key_string('levelone1.leveltwo2.c', $a); //Returns 'abc' Kohana::key_string('levelone2.foo', $a); //Returns 'bar'
list_files()
Iteratesthroughalldirectoriesofagivennameandreturnsfoundfiles.Ittakestwoparameters:
[string]Inwhichdirectorytosearchin [bool]Shouldfind_filesberecursive?(TRUEorFALSE,defaultstoFALSE)
Itreturnsarrayoffilepathstofoundfiles. Example
$controllers = Kohana::list_files('controllers', TRUE); // Now $controllers is an array containing paths to all controllers in your Kohana installation
find_file()
FindaresourcefileinagivendirectoryusingKohana'scascadingfilesystem.
Example
// find a file named 'database.php' in the 'config' directory. include (Kohana::find_file('config','database'));
LogClass
Providesmethodstoworkwithlogging.
Configuration
TheconfigurationfileLog.phpcanbefoundintheapplication/configdirectory.Ifit'snot thereitcanbecopiedfromthesystem/configdirectory.Seeformoreinformationonthe Configpage. TherearethreesettingsfortheLogclass:
$config['threshold'] = 0; $config['directory'] = 'logs'; $config['format'] = 'Y-m-d H:i:s';
$config['threshold'] canbesetatfourlevels:
Methods
Addingentriestothelogfile
Log::add($type, $message)logsthemessageaccordingtothetypegiven (error,debug,info),theitemwillbeprecededbyatimestampformattedaccordingto $config['format'].
Log::add('error', 'Query went wrong'); // returns void Log::add('debug', 'Custom library X loaded'); // returns void
Writingthelogentriestothefile
Log::write()iscalledbydefaultontheshutdownevent(event.shutdown).Seeformore informationoneventstheEventpage.Thereistypicallynoneedtocallitmanually.
Log::write(); // returns void
UnicodeFunctions
ProvidesstaticmethodstoworkwithUTF8stringsasPHPisnotyetnativelycapableofdoingthat. Requirements:
Methods
clean
utf8::clean()recursivelycleansarrays,objects,andstrings.ItremovesASCIIcontrol characters(strip_ascii_ctrl)andconvertstoUTF8whilesilentlydiscardingincompatible UTF8characters. Note: Theclean()methodisautomaticallyappliedtotheGET,POST,COOKIEandSERVERglobals.
from_unicode is_ascii
utf8::is_ascii()checkswhetherastringcontainsonly7bitASCIIbytes.ItreturnsTRUEif itdoesso,FALSEotherwise.Thismethodisalsousedinternallyintheutf8classtodeterminewhen tousenativefunctionsorUTF8functions. Example:
var_dump(utf8::is_ascii("a\0b".chr(127).'c')); // bool(true)
var_dump(utf8::is_ascii("a\0b".chr(128).'c')); // bool(false)
strip_non_ascii
utf8::strip_non_ascii()removesallnonASCIIcharactersfromastring. Example:
echo utf8::strip_non_ascii('Clichs'); // Output: Clichs
stristr strlen strpos strrev strrpos strspn strtolower strtoupper substr substr_replace to_unicode transliterate_to_ascii
utf8::transliterate_to_ascii()replacesmany(notall)special/accentedcharactersby theirASCIIequivalents.Specialcharactersthatareunknowntothismethodareleftuntouched.You canremovethemafterwardswiththestrip_non_asciimethod. Example:
echo utf8::transliterate_to_ascii('Jrme est un garon.'); // Output: Jerome est un garcon.
Furtherreading:Wikipediaontransliteration
ViewClass
ForamoreindepthoverviewofviewsseeGeneral/Views.
Creatinganinstance
Creatinganinstanceoftheviewclass.
$view = new View('welcome');
Settingdata Methods
set()
set()canbeusedtosetavariableinaview.Youcanalsosupplyanarrayandthekeysandvalues willbetreatedasvariables.$thisviewyour_variablecanbeusedtoaccomplishthesame.
$view = new View('welcome'); $view->set('title', 'Elvis lives');
bind()
bind()islikesetonlythevariableisassignedbyreference.
$view = new View('welcome'); $var='Some value'; $view->bind('title', $var); $var='Another value'; $view->render(true); //The 'title' variable will contain 'Another value'
set_global()
set_global()islikesetonlythatthevariablessetareavailablethroughoutallviews.This meansyoucanuseitwithviewsinviewsforexample.
// loading views $view = new View('page'); $view->header = new View('header'); // setting variables in all views $view->set_global('title', 'Title of page'); // set variable $title for example in view header.php $view->render(TRUE);
render()
render()renderstheoutputoftheView.
// render and store, default, no browser output $this->template->content = $this->session->get_once('message').$content-
factory()
Thismethodisstatic.Parametersarethesameascreatinganewinstance. ItcreatesaViewinstanceandimmediatelyreturnsitsomethodchainingispossible.
public function _add_breadcrumb() { $crumbs = View::factory('admin/breadcrumb') ->set('crumbs', html::breadcrumb()) ->render(); } $this->template->content = $crumbs.$this->template->content;
set_filename()
Thismethodonlyexistsinversion2.2 set_filename()setsthenameofthefileusedfortheview.
$view=new View; if(request::is_ajax()) //request helper also exists in 2.2 { $view->set_filename('ajax_view'); } else { $view->set_filename('html_view'); } $view->render(TRUE);
Addons
AuthModule
TheAuthmoduleisasimplemoduletoenableauthenticationonyoursite.Itsupportsusers, multiplerolesperuserandautologins.ItemploysORMandForge.Ifyou'renewtoKohanathe codeofAuthmighthelpyoutogetstarted.Takealookatthecontrollerandthemodelstoseehow simpleapplicationswork.
Methods
auto_login() login()
$thisauthlogin($user, $password, $remember)validatesauser'sauthentication credentialsandlogsauserin.
logout()
$thisauthlogout($destroy)logsauseroutbyremovingtheappropriatesession variables.
[boolean]Iftrue,completelydestroythesession;iffalse,donotdeletethesession,butonly removetheauthenticationinformationfromthesession.
hash_password()
ForgeModule(FormGeneration)
TheForgemoduleisamoduletoeasilycreateandmanageforms.Youcancreateformswithbuilt invalidationinonego.ForgecoexistswiththeFormhelpers,itdoesn'treplaceit.Forgeprovides helpwithrendering,validatingandfilteringforms,theformhelperprovidesmethodstocreate forms.
Creatingaform
CreatingaformisdonebyinstantiatingtheForgeclass
$form = new Forge('', 'Add article', 'POST', array('id' => 'article_form'));
Addingelements
Nextstepisaddingelements.
$form->input('title');
Thisisthebasisofaddingelements.Nowwesetalabelandaddrules.
$form->input('title')->label(true)->rules('required|length[3,40]| valid_alpha_numeric')->value('title');
Acompleteform
$form = new Forge('', 'Add article','POST',array('id' => 'article_form')); $form->set_attr('class', 'form_class')->set_attr('method', 'post'); $form->input('title')->label(true)->rules('required|length[3,40]| valid_alpha_numeric'); $form->input('article')->label('Article text')->rules('required|| valid_alpha_numeric'); $form->submit('submit'); if($form->validate()) { echo $form->title->value; echo $form->article->value; } else { echo $form->html(); }
Formmethods
set_attr() set_attr()setanattributeofthe<form>element.Therearetwoparameters:
[array]/[string]Eithertheattributenameoranarrayofattributenamesandvalues [string]Attributevalue(DefaultNULL)
$form = new Forge('', 'Add article', 'post',array('id', 'article_form')); $form->set_attr('class', 'form_class'); $form->set_attr(array('class' => 'form_class','id' => 'article_form'));
FormElements
NotethatallelementsexceptforForm_GroupinheritfromForm_Inputsomethodsbelowapplyto allofthem.
Form_Input
Createinput Createaninput.Methodischainable.
$form->input('input_name');
or
->label('Custom input name');
Inputvalidation Setthevalidationrulesforthefield.Methodischainable.
->rules('list|of|validation|rules')
Inputvalue Setthedefaultvaluefortheelement.Methodischainable.
->value('input_value')
Example
$form->input('title')->label(TRUE)->rules('required|length[0,255]')>value($this->page->title);
Form_Checkbox
Bydefaultacheckboxcheckedstatusisofftoturnonjustcallthecheckedmethodandsettotrue. Example
$form->checkbox('test')->label(TRUE)->value('1')->checked(TRUE);
Form_Checklist
Example
$form->checklist('blocks')->label('Blocks available')->options($option)>rules('required');
Form_Dateselect
Example
$form->dateselect('date')->label(TRUE)->years(date('Y')-3, date('Y')+5)>value(strtotime($your_date_var));
Form_Dropdown
Youcansetdropdownwithsinglearrayorwithtwodimensionalarray.Thekeywillbetheoption valueandthevaluewillbetheoptiontext. Example
$form->dropdown('pizzas')->label(TRUE)->options(array('Hawaiian', 'Margarita'))-
Form_Group
IsaninstanceoftheForgeclasssoyoucanhavegroupsinyourforms.AllmethodsoftheForge classareavailablesavehtml(). Example
$group = $form->group('pizzas')->label(TRUE); $group->dropdown('pizzas')->label(TRUE)->options(array('Hawaiian', 'Margarita'))->selected('1'); $group->dropdown('bases')->label(TRUE)->options(array('Thin', 'Pan', 'Stuffed'))->selected('2');
Intheviewgroupsgetspecialattentionandarerendereddifferently.Youcanusegroupsfor examplewhenyouneedtogroupsomeformelementswithina`<fieldset>`tag.
Form_Hidden
Inthedefaulttemplatehiddenformsareaddedstraightafterthe<form>tag. Example
$form->hidden('id')->value(1);
Form_Password
Themethod'matches'matchesaformfieldwithanotherformfield. Example
$form->input('password')->label(TRUE); $form->input('passconf')->label('Password Confirmation')->rules('required| length[5,32]')->matches($form->password);
Form_Submit
Example
$form->submit('Submit Button Name');
Form_Textarea
Example
$form->textarea('description')->label(TRUE)->rules('length[0,255]')>value($this->page->description);
Form_Upload
Example Ifthefileexistsandthesecondargumentofupload()methodisTRUE,itwilloverwritethisfile. Otherwiseitwillcreateanuniquename.
$form->upload('file', TRUE)->label(TRUE)->rules('required|size[200KB]| allow[jpg,png,gif]');
Thedefaultuploadpathisconfiguredyourupload.phpconfigfile(system/config/upload.php).
UsingCustomFormTemplates
Ifyouneedmorecontroloveryourform,butstillwanttotakeadvantageoftheautomatedvalidation andfieldrepopulationprovidedbytheForgelibrary,youcanutilizeacustomformtemplate.This allowsyoutodesigntheformhoweveryouwantusingHTML. from:http://forumarchive.kohanaphp.com/index.php/topic,616.msg3841.html#msg3841 Example Controller:application/controllers/your_controller.php
$form = new Forge(); $form->input('username')->label(TRUE)->rules('required'); $form->password('password')->label(TRUE)->rules('required'); if ($form->validate()) { // Do stuff } echo $form->html('login_form', TRUE); use a custom form // Only this is different, specifies to
View:application/views/login_form.php
<form method="post" action="<?= url::site('login') ?>"> <?= $username->label() ?> <br /> <?= $username->html() ?> <br /> <?= $username_errors ?> <br /><br /> <?= $password->label() ?> <br /> <?= $password->html() ?> <br /> <?= $password_errors ?> <br /> <input type="submit" value="Login" /> </form>
Savingformsasalibrary
UsingForgeyoucansaveformsasalibraryandthushaveaccesstoyourformthroughoutyour application.Seehttp://learn.kohanaphp.com/2008/03/13/savingformsaslibraries/forashort tutorial.
MediaModule
TheMediaModuleisusedtoreducethenumberandbandwidthofqueriesforCSSandJavaScript files.Itdoesnotsupportimagesatthecurrenttime. Oncethemodulehasbeenenabledinthestandardway,itwillinterceptrequestsfor /media/css/and/media/js/transformingtheresultsasspecifiedintheconfigfile media.php.
Configuration
readtheconfigfornow
Usage
PlaceallCSSfilesintothedirectory/application/views/media/css/andallJavaScriptfilesinto /application/views/media/js/. Youthenusethehelperstoincludethemfromyourviewpageslikethis:
<?=media::stylesheet(array('sheet1', 'sheet2', 'sheet3'))?> <?=media::script(array('jquery', 'dojo'))?>
Nottoconfusematterstheaboveissimplyahelperforwritingthefollowing:
<link rel="stylesheet" href="/media/css/sheet1,sheet2,sheet3.css" type="text/css" /> <script type="text/javascript" src="/media/js/jquery,dojo.js"></script>
TemplateController
TemplateController
Usingthetemplatecontrolleryoucansetatemplateforyoursite.It'sworkingsaresimple. Example:application/controllers/home.php
class Home_Controller extends Template_Controller{ public $template = 'template'; //defaults to template but you can set your own view file public $auto_render = TRUE; //defaults to true, renders the template after the controller method is done public function __construct() {
Example1
ThisisasimpleexamplethatshowsthemagicoftheTemplateclass. Savethisas/application/controllers/test.php
class Test_Controller extends Template_Controller { public $template = 'base_page'; public function __construct() { parent::__construct(); // // // // the template page 'base_page' is loaded by default, this is the same as uncommenting the following line: $this->template = new View('base_page');
// All pages have some things in common such as // the page title: $this->template->title = "Welcome to Kohana!"; $this->template->copyright = "© Me, 2008"; } function index() { // // don't forget that the __construct() is run // before this method, so the template // is set up and ready for this pages content. // // Load this page (Test) view $test = new View('test'); // now create this page (Test) $test->heading = "Test :: Index Heading"; $test->content = "Test :: Index :: content here."; $test->content .= '<br><a href="test_2">page 2</a>'; // add our content to the template view: $this->template->content = $test;
function test_2() { // Load this page (Test) view $test = new View('test'); // now create this page (Test) $test->heading = "Test :: test_2 :: Heading"; $test->content = "Test :: test_2 :: content here."; $test->content .= '<br><a href="index">page 1</a>'; // add our content to the base view: $this->template->content = $test; // the view is auto-render by default } }
Thisusesthefollowing2views: Savethisas/application/views/base_page.php
<html> <head> <title><?php echo $title; ?></title> </head> <body> <?php echo $content ?> <?php echo $copyright; ?> </body> </html>
Savethisas/application/views/test.php
<h1><?php echo $heading; ?></h1> <p><?= $content ?></p>
Example2
Itiseasytoaddmoreinterestingthingsintheconstruct()suchascustomnavigationmenusfor this'testsection'ofyourwebsite.Forexample,alterthemethod:
public function __construct() { parent::__construct(); $this->template->title = "Welcome to Kohana!"; $this->template->copyright = "© Me, 2008"; // Look: $this->template->menu = new View('test_menu');
Savethisas/application/views/test_menu.php
<div style="width: 100px; float: right; border: 1px solid lightgreen;"> <ul> <li>menu 1</li> <li>menu 1</li> </ul> </div>
Alter/application/views/base_page.phptodisplaythemenu:
<html> <head> <title><?php echo $title; ?></title> </head> <body> <?php echo $menu ?> <?php echo $content ?> <?php echo $copyright; ?> </body> </html>
Obviouslyyou'llneedtoaddsomemeaningfulcontenttotheviews
Libraries
ArchiveLibrary
Overview
TheArchiveLibraryisaconvenientwayofconstructingArchives(ZipFiles,TarFiles,etc) dynamically.Itcanpersistthemtothefilesystem,oritcansendthebinaryfiledirectlytotheuser withoutsavingtotheharddrive. CurrentlyitonlysupportsZipArchives.
Loadingthearchivelibrary
TheArchiveclassisloadedintoyourcontrollerusing$thisloadlibrary:
//load the archive class with the Zip driver to create Zip archives $this->archive=new Archive('zip');
Methods
add()
add()addsfilesanddirectoriestoyourarchive.Itacceptsthefollowingparameter:
[string]pathtofileordir.Relativepathsmustberelativetotherootwebsitedir. [boolean]whethertoscanthedirrecursivelydefault=TRUE
Thiswillresultinfile.txtbeingaddedtothearchive:
$this->archive->add("files/uploads/file.txt");
save()
save()savesthearchiveyou'vebeencreatingtothedisk.
[string]pathtosavethearchivefile.Relativepathsmustberelativetotherootwebsitedir.
$this->archive->save("myarchive.zip");
download()
download()offersthearchiveasadownloadtotheuser.
[string]nametobegiventothearchivefile
$this->archive->download("myarchive.zip");
CacheLibrary
Kohana'scachelibrarycancurrentlystorecachesinafileorSQlite.Thisisconfigurablebysetting thedriver.Itutilizestagsandid'stoidentifycaches. FortheAPIdocumentation:
notavailableyet
ViewthepagecachingscreencastfromWoodyGilk(Shadowhand).
Configuration
Configurationisdoneintheapplication/config/cache.phpfile,ifit'snottheretaketheonefrom system/configandcopyit.
$config['driver'] = 'file'; $config['params'] = APPPATH . 'cache'; $config['lifetime'] = 1800; $config['requests'] = 1000;
Methods Loadingthelibrary
$this->cache= new Cache;
Settingcaches
set $thiscacheset($id,$data,$tags = NULL, $lifetime = NULL)isusedtoset
caches.
Findingandgettingcaches
get $thiscacheget($id)retrievesacachewiththegiven$id,returnsthedataorNULL
print_r($this->cache->get('existentialists')); //returns: // Array ( [0] => Jean Paul Sartre [1] => Albert Camus [2] => Simone de Beauvoir )
find $thiscachefind($tag)supplywithastring,retrievesallcacheswiththegiventag.
$food=array('French bread','French wine','French cheese'); $this->cache->set('food',$food,array('french')); print_r($this->cache->find('french')); //returns //Array ( [existentialists] => Array ( [0] => Jean Paul Sartre [1] => Albert Camus [2] => Simone de Beauvoir ) [food] => Array ( [0] => French bread [1] => French wine [2] => French cheese) )
Deletingcaches
Thereareseveralmethodstodeletecaches delete $thiscachedelete($id)deletesacacheitembyid,returnsaboolean
$this->cache->delete('food');
delete_tag $thiscachedelete_tag($tag)deletesallcacheitemswithagiventag,returnsaboolean
$this->cache->delete_tag('french');
delete_all $thiscachedelete_all()deletesallcacheitems,returnsaboolean
$this->cache->delete_all();
SQLiteDriverSchema
IfyouusetheSQlitedrivertostorethecachesthetablecanbeconstructedwiththisquery.
CREATE TABLE caches( id varchar(127), hash char(40), tags varchar(255), expiration int, cache blob);
CalendarLibrary
Overview
Providesmethodsforgeneratingandworkingwithacalendar.Thelibraryoutputsacalendarmonth inHTML,foruseinthesystemviewsystem/views/kohana_calendar.php
Loadingthecalendarlibrary
TheCalendarclassisloadedintoyourcontrollerusing:
$this->calendar = new Calendar();
Accesstothelibraryisavailablethrough$thiscalendar Theparametersofthisconstructorare:
Example
$cal = new Calendar(1,2008); // January, 2008. The default is current month and year echo $cal->render(); // the view is automatically rendered from the library
20 27
21 28
22 29
23 30
24 31
25 26 1 2
Adjustingthecalendar
Thelayoutofthecalendarcanbeadjustedbycreatingthefollowingfile:application/views/ kohana_calendar.phpThenativeKohanacalendarfilecanbecopiedfrom system/views/kohana_calendar.phptohavetemplatetostartworkingfrom.
DatabaseLibrary
Thedatabaselibraryprovidesdatabaseaccesstoyourapplicationusingdrivers. Currentlywehavethefollowingdriversavailable: 1. 2. 3. 4. MySQL MySQLi PostgreSQL PDOSqlite(availableinSVN)
TableofContents
QuickExamples
Thefollowingisexamplecodeforusingcommondatabasefunctionality.Formoreindepthhelp pleasereadtheindividualtopicslinkedabove. Initializingthedatabase
$db = new Database(); // or $db = new Database('groupname'); given // "default" is assumed if groupname is not
SimpleQuery
$result = $db->query('SELECT username,password,email FROM users'); foreach ($result as $row) { echo $row->username; echo $row->password;
echo $row->email; }
QuickExample2
Thisdemonstratesusingthequeryresultsinatemplate. Query
class Clients_Controller extends Controller { public function index() { $db = new Database; $result = $db->query('SELECT name, code FROM clients'); $v = new View('clients'); $v->result = $result; $v->render(TRUE); }
Template
<html> <head> <style> /* * Zebra rows: When CSS3 is done we could simply use: * tr :nth-child(odd) { background-color: #D0D0D0; } * but for now we use PHP and CSS */ table.db tr { background-color: #F0F0F0; } table.db tr.odd { background-color: #D0D0D0; } table.db th { color: #f0f0f0; background-color: #303030; } </style> </head> <body> <h2>Client List</h2> <hr/> <table class="db"> <tr> <th>Client</th> <th>ID</th> </tr> <?php foreach( $result as $row ):?> <tr <?= text::alternate( '', ' class="odd"' ) ?>> <td><?= $row->name ?> </td> <td><?= $row->code ?> </td> </tr> <?php endforeach; ?> </table> </body>
EncryptLibrary
Overview
TheEncryptLibraryprovidesaneasywaytoencryptanddecryptdatausingsymmetrickeys. Youcanchoosewhatcypheryou'dlikethealgorithmtouseandyoucanspecifyyourownkeyfor theencryption.
Loadingtheencryptionlibrary
TheEncryptionclassisloadedintoyourcontrollerusing$thisloadlibrary:
$this->encrypt=new Encrypt;
Accesstothelibraryisavailablethrough$thisencrypt
Configuration
Configurationisdoneinapplication/config/encryption.phpifit'snottheretakethe onefromsystem/configandcopyit.
$config['key'] = 'YOUR CYPHER KEY'; $config['mode'] = MCRYPT_MODE_NOFB; $config['cipher'] = MCRYPT_RIJNDAEL_128;
Methods
encode($data)
$thisencryptencode($data)returnsanencryptedversionof$datausingthecipher andkeyspecifiedintheconfigurationfile.
$encrypted_text = $this->encrypt->encode('The Answer is 42'); echo $encrypted_text;
decode($encrypted)
$thisencryptdecode($encrypted)returnsadecryptedversionof$encryptedusing thecipherandkeyspecifiedintheconfigurationfile.
$encrypted_text = $this->encrypt->encode('The Answer is 42'); echo $this->encrypt->decode($encrypted_text);
ImageLibrary
Providesmethodsforthedynamicmanipulationofimages.VariousimageformatssuchasJPEG, PNG,andGIFcanberesized,cropped,rotatedandsharpened. Allimagemanipulationsareappliedtoatemporaryimage.Onlythesave()methodis permanent,thetemporaryimagebeingwrittentoaspecifiedimagefile. Imagemanipulationmethodscanbechainedefficiently.Recommendedorder:resize,crop, sharpen,qualityandrotateorflip
LoadingtheImagelibrary
Usesadriver,configuredinconfig/image.php.ThedefaultdriverusestheGD2library, bundledwithPHP.ImageMagickmaybeusedifavailable. Whenloadingthelibrary,apathtotheimagefile,(relativeorabsolute)mustbepassedasa parameter. LoadtheImageLibraryinyourcontrollerusingthenewkeyword:
$this->image = new Image('./photo.jpg');
Accesstothelibraryisavailablethrough$thisimageSomemethodsarechainable.
Methods
resize()
resize()isusedtoresizeanimage.Thismethodischainable.Bydefault,theaspectratiowillbe maintainedautomatically.
Example:
// Resize original image to Height of 200 pixels, using height to maintain aspect ratio. $this->image->resize(400, 200, Image::HEIGHT) // Note: Passing width = 400 has no effect on the resized width, which is controlled by the 3rd argument, maintain aspect ratio on height $this->image->resize(400, 200, Image::NONE) //Note: The output image is resized to width of 400 and height of 200, without maintaining the aspect ratio
crop()
crop()isusedtocropanimagetoaspecificwidthandheight.Thismethodischainable. Thetopandleftoffsetsmaybespecified.Bydefault'top'and'left'usethe'center'offset.
Example:
// Crop from the original image, starting from the 'center' of the image from the 'top' and the 'center' of the image from the 'left' // to a width of 400 and height of 350. $this->image->crop(400, 350)
rotate()
rotate()isusedtorotateanimagebyaspecifiednumberofdegrees.Thismethodischainable. Theimagemayberotatedclockwiseoranticlockwise,byamaximumof180degrees.
[integer]Degreestorotate.(negativerotatesanticlockwise)Thereisnodefault.
Example:
// Rotate the image by 45 degrees to the 'left' or anti-clockwise. $this->image->rotate(-45)
flip()
flip()isusedtorotateanimagealongthehorizontalorverticalaxis.Themethodischainable.
[integer]Direction.Horizontal=5,Vertical=6
Example:
// Rotate the image along the vertical access. $this->image->flip(6);
sharpen()
sharpen()Isusedtosharpenanimagebyaspecifiedamount.Thismethodischainable.
[integer]Sharpenamounttoapplytoimage.Rangeisbetween1and100.Optimalamountis about20.Thereisnodefault.
Example:
// Sharpen the image by an amount of 15. $this->image->sharpen(15);
quality()
quality()Isusedtoadjusttheimagequalitybyaspecifiedpercentage.Thismethodis chainable. Note:Themethodisforreducingthequalityofanimage,inordertoreducethefilesizeofthe image,savingbandwidthandloadtime.Itcannotbeusedtoactuallyimprovethequalityofaninput image.
[integer]Percentageamounttoadjustquality.Rangeisbetween1and100.Optimal
percentageisfrom75to85.Thereisnodefault. Example:
// Reduce image quality to 75 percent of original $this->image->quality(75);
save()
save()Isusedtosavetheimagetoafileondisk.ThismethodisNOTchainable.Thedefaultisto overwritetheinputimagefile.Acceptsarelativeorabsolutefilepath.
[string]Thefilepathandoutputimagefilename.Defaultistooverwriteinputfile.
Example:
// Save image and overwrite the input image file $this->image->save(); // $this->image->save('./new-image.jpg'); // Save image to a new file.
FullExample
Placethiscodeintoacontroller
// The original image is located in folder /application/upload. $dir = str_replace('\\', '/', realpath(dirname(__FILE__).'/../upload')).'/'; $image = new Image($dir.'moo.jpg'); // Instantiate the library $image->resize(400, NULL)->crop(400, 350, 'top')->sharpen(20)->quality(75); // apply image manipulations $image->save($dir.'super-cow-crop.jpg'); // Write the changed image to a new file in the original input folder echo Kohana::debug($image); // Display some useful info about the operation **for debugging only**.
InputLibrary
Theinputlibraryisusefulfortwothings:preprocessglobalinputforsecurityprovidesome usefulfunctionsforretrievinginputdata Note:
Loadingthelibrary
Thislibraryisautomaticallyloadedbythecontrollersoyoudon'tneedtoloadityourself.Itis accessedby$thisinputinthecontrollerscope.
Methods
get()
allowsyoutoretrieveGETvariables.ifglobalXSSfilteringison(config)thendatareturnedbythis functionwillbefiltered.
[string]variabletoretrievedefault=emptyarray(returnsallvariables)
//URL is http://www.example.com/index.php?articleId=123&file=text.txt //Note that print statements are for documentation purpose only print Kohana::debug($this->input->get()); print Kohana::debug($this->input->get('file'));
ItwillresultinHTMLas:
Array ( [articleId] => 123 [file] => text.txt ) text.txt
YoucanalsomanuallyXSScleantherequestbypassingTRUEasthesecondparameter.
post()
allowsyoutoretrievePOSTvariables.ifglobalXSSfilteringison(config)thendatareturnedby thisfunctionwillbefiltered.
[string]variabletoretrievedefault=emptyarray(returnsallvariables)
//POST variables are articleId=123 and file=text.txt //Note that print statements are for documentation purpose only print Kohana::debug($this->input->post()); print Kohana::debug($this->input->post('file'));
ItwillresultinHTMLas:
Array ( [articleId] => 123 [file] => text.txt ) text.txt
YoucanalsomanuallyXSScleantherequestbypassingTRUEasthesecondparameter.
cookie()
allowsyoutoretrieveCOOKIEvariables.ifglobalXSSfilteringison(config)thendatareturned bythisfunctionwillbefiltered.
[string]variabletoretrievedefault=emptyarray(returnsallvariables)
//COOKIE name is "username" and the contents of this cookie is "aart-jan". //Note that print statements are for documentation purpose only print Kohana::debug($this->input->cookie()); print Kohana::debug($this->input->cookie('username'));
ItwillresultinHTMLas:
Array ( [username] => aart-jan ) aart-jan
YoucanalsomanuallyXSScleantherequestbypassingTRUEasthesecondparameter.
server()
allowsyoutoretrieveSERVERvariables.ifglobalXSSfilteringison(config)thendatareturned bythisfunctionwillbefiltered.
[string]variabletoretrievedefault=emptyarray(returnsallvariables)
//Note that print statements are for documentation purpose only print Kohana::debug($this->input->server('HTTP_HOST')); //this example ran on a local server
ItwillresultinHTMLas:
localhost
YoucanalsomanuallyXSScleantherequestbypassingTRUEasthesecondparameter.
ip_address()
'ip_address'returnstheIPaddressoftheuservisitingusingyourwebapplication.Itreturns'0.0.0.0' ifthere'snoIP.
print $this->input->ip_address(); //this example ran on a local server
ItwillresultinHTMLas:
127.0.0.1
valid_ip()
'valid_ip'willcheckwhetherthespecifiedIPisavalidIPV4ipaddressaccordingtotheRFC specifications.
[string]IPaddresstobevalidated
ThisfunctionisidenticaltotheIPaddressvalidationhelper.
user_agent()
'user_agent'returnstheuseragentofthecurrentrequest.Becareful!EvenifglobalXSSfilteringis on,thedatareturnedbythisfunctionwillnotbefiltered!
print $this->input->user_agent();
ThiscouldresultinHTMLas:
Mozilla/5.0 (Windows; U; Windows NT 6.0; nl; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11
xss_clean()
allowsyoutocleanastringtomakesureitissafe.
[string/array]Thestringorthearrayofstringstoclean
echo $this->input->xss_clean($suspect_input);
ORMLibrary
TheORMlibraryistheObjectRelationalmapperforKohana.Itprovideswaystohandlerecordsin yourdatabaseasiftheywereobjectsanditmanagesrelationshipsbetweenyourtables.Itisnot loadedlikeotherlibrariesbutworksinthemodel.Forexample,ifyouhaveatableusers(plural) youwouldhaveamodelUser_Model(singular)inyourapplication/modelsdirectoryasfollows: user.php
class User_Model extends ORM { }
IfyouplantooverridetheconstructoroftheORMmodelyouneedthiscode:
class User_Model extends ORM { public function __construct($id=FALSE) { parent::__construct($id); } }
ORMconventions
InorderforORMtoworkproperlytherearesomeconventionsthatmustbeupheld.
Relationships
Relationshipsaredeclaredinthemodel.
protected protected protected protected protected $has_one = array(); $has_many = array(); $belongs_to = array(); $belongs_to_many = array(); $has_and_belongs_to_many = array();
Itisvitalyouusepluralizationandsingularizationcorrectly.E.g
Class Dorm_Model{ protected $has_many=array('students');//plural - a dorm has many students } class Student_Model{ protected $belongs_to=array('dorm'); //singular, - a student belongs to (one) dorm }
ThesetutorialscanhelpyouwithrelationshipsinORM.
Atutorialonthehas_one/belongs_torelationship Atutorialonthehas_many/belongs_torelationship
AnoteaboutORMrelationshipsinKohana:
InORM,whenarelationshipstartswithhas_itshowsownership,orifyouwanttothinkofit anotherway,parentandchild.So,whenyouhaveusersandroles,theusers has_and_belong_to_manyroles,butrolesjustbelong_to_manyusers.Theprimaryreasonforthisis toenabletheORMlibrarytochoosewhichtablenamecomesfirstinajoining/pivottable.Inthe exampleofusersandroles,becauseusersownroles,thetableiscalledusers_roles. Intheory,youcouldfliptherelationship,butORMrestrictsfindingtoobjectsthatownother objects.Forinstance,ifyouusedrolesastheownerobject,youwouldnotbeabletodo $userfind_related_roles(),butyouwouldbeabletodo$rolefind_related_users().Inreality,it makessensethattheusercanfindtherolestheyown.ORMdoesnotyetsupportthisfromboth directions.
ORMFactorymethod
Youcanalsousethefactorymethodtomakechainingofmethodseasier.
$users=ORM::factory('user')->find_all_by_email('example@example.com'); //equivalent to $user=new User_Model; $users=$user->find_all_by_email('example@example.com');
Itgetstheusermodel,findsallrecordswithacertainemailaddress.Youcanalsousethesecond argumenttoquicklyfindarecord.
$user=ORM::factory('user',1); $user->delete(); //equivalent to $user=new User_Model(1); $user->delete();
Gettheuserwithid=1anddeleteitinthesecondline.
Methods
find()
find()isusedtofindasinglerecordinatableifyousupplytheidoftherecord.Canalsoreturn allrecordsifyousupplytheconstantALL Example
$user=new User_Model(); $user->find(1); echo $user->email; //outputs the field email of table users of record with id = 1 $user->find(ALL); // see find_all();
find_all
find_allisequaltofind(ALL)
foreach($user->find_all() as $person){ echo $person->email; } //output emails of all users
find_by
find_bysetsthemodeltothefirstrecordthatmatchesthecriterion.Thismethodischainable.
$user=new User_Model; $user->find_by_email('example@example.com');
Avariationisyoucanusemultiplevalues,eg:
$user->find_by_email_and_password('example@example.com', 'secret');
or
$user->find_by_email_or_username('example@example.com', 'example');
Youcanuseanynumberofvalues,butyoucanonlyuseeither_and_or_or_,notboth.
find_all_by
find_all_byreturnsanarrayofallrecordsthatmatchthecriterion
Youcanuse_and_or_or_,justlikefind_by(seeabove).
find_related_
find_related_returnstheallrelatedrecords.Youmustsetarelationshipinthemodelforthis towork.
$user=new User_Model; $user->find(1); $user->find_related_pages(); //finds all related pages to user with id = 1
has
Testforexistenceofrelationship. Forexampleif$has_many = array('dogs')thenyoucantestforarelationship
if($pet_enthusiast->has_dog($dog)) { echo 'He has a dog!'; }
add
Usedwiththerelationshipsdefinedinthemodeltoprovidehandyrelationshipmethods. Forexampleif$has_many = array('dogs')thenyoumay $pet_enthusiastadd_dog($dog). Syntax
/** * @param mixed $var Can be an object, an array of strings which associate to object models, or a string which will be found using $model->find($var) * @return bool Can also return the boolean result from $model->save() */ $object->add_$model(mixed $var);
remove
Removesthe$dogfromthe$pet_enthusiast. Syntax
/** * @param mixed $var Can be an object, an array of strings which associate to object models, or a string which will be found using $model->find($var) * @return bool Can also return the boolean result from $model->save() */ $object->remove_$model(mixed $var);
save
savesavesanobjecttothedatabase.Ifitdoesn'texistitusesanINSERTstatement,ifitdoesit usesanUPDATEstatement. Insertexample
$user=new User_Model; $user->email='test@test.com'; $user->save(); //will insert a new user into the table with email being 'test@test.com'
Updateexample
$user=new User_Model; $user->find_by_email('test@test.com'); $user->email('example@example.com'); $user->save(); //will update a the test@test.com user with a new email example@example.com
delete
deletedeletesthecurrentobject.
$user=new User_Model; $user->find(1); $user->delete();
delete_all
delete_alldeletesallrecordsinthetable.
$user=new User_Model; $user->delete_all(); //alternate syntax $user->delete(ALL);
loaded clear
Emptiesanobjectsettingitspropertiesto''.Alsoresetsselectandwhere
as_array
Returnstheobjectasanarraywithkey/valuepairs.
Properties
where
Whichcriteriashouldthequeryuse.
$user=new User_Model; $user->where('role','admin'); $user->find_by_email('example@example.com');
Willaddextracriterion,roleshouldbeadmin.
select
Whichfieldstofetch
$user=new User_Model; $user->select('email'); $user->find_by_email('example@example.com');
Willonlyselecttheemailfield.
auto_save
IfsettoTRUEexecutesave()onthedestructionoftheobject.Youthendon'thavetocall save()manually.Ifit'ssettoFALSEandyoudon'tcallsave()meanslosingchangesmadeto theobject.
DefaultstoFALSE
UsingDBBuildermethods
InKohana'sORMyoucanstillusesomeofthemethodsoftheDBbuilder Example
//Fetch the latest 10 articles $articles=new Article_Model(); $articles=$articles->orderby('id','desc')->limit(10)->find_all();
Thefollowingdbbuildermethodscannotbeused
Note:whenchainingmethodslikethis,find_all()orfind(),find_by()etc.needstobelastsinceit willexecutetheactualquery.
Changingthewherekey
Bedefaultthefind()methodwillusethe'id'fieldasacriterionforselectingrecords.I.e.find(1) willreturntherecordwithid=1.ThesamegoesfornewUser_Model(1)syntax.Inyourmodelyou canoverridethewhere_key()methodsoyoucanchangethedefaultcriterionfield. user.php
class User_Model extends ORM { protected function where_key($id = NULL) { return 'name'; } }
PaginationLibrary
ThePaginationlibraryautomaticallygeneratesstyledlinkslike,First<12345>Last fornavigatingthroughpagesinawebsite. ThelinksrefertothePagenumberandNottheoffsetofthedata. Thelibraryiseasilyconfigurable.DefaultPaginationSettingsarelocatedin system/config/pagination.php.Youcanoverridethesystemsettingsbycreatinga paginationconfigfileinyourapplication/configorbypassingconfigurationsettingstothe libraryatruntime. Pleasenotethatthelibrarydoesnotinteractwithyourdatainanyway,itgenerateslinks.The developermustwritethecodethatfetchesthedatareferredtobythelinks.Amethodisprovidedto helpcalculateSQLoffsets. ThepagelinksaregeneratedusingaViewfilelocatedinsystem/views/pagination.Four stylesareprovided.Youmayeditthesetosuityourneeds,oryoucancreateanew,custom paginationview.Youmayalsooverridethesystemstylesbycopyingtheviewstoyour application/views/paginationdirectory.
LoadingthePaginationlibrary
LoadthePaginationclassinyourcontrollerusingthenewkeyword Configurationsettingsareobtainedfromconfig/pagination.phpSettingsmayalsobe passeddynamicallytotheclassasanarray.
$this->pagination = new Pagination($config);
Accesstothelibraryisavailablethrough$thispagination
Methods
initialize()
$thispaginationinitialize()isusedtodynamicallysetpaginationconfiguration.Itis automaticallycalledbythelibraryconstructor,sothereisnoneedtocallthismethodexplicitly, unlessyouwishtooverwriteaconfigsettingdynamically.
// Will overwrite only the existing setting for this config item $this->pagination->initialize(array('uri_segment' => 'pages'));
create_links()
InKohana2.2create_links()hasbeenrenamedtorender(). $thispaginationcreate_links()isusedtogeneratethelinkoutputfordisplay.Allows youtoselectthepaginationstyledynamically.Pleasenote:Thelinksmayalsobeoutputbysimply echoing$thispagination
// Will overwrite the default 'classic' style with 'digg' style $this->pagination->create_links('digg'));
sql_offset()
Note:thismethodisdeprecatedinversion2.1use$thispaginationsql_offset propertyinstead. $thispaginationsql_offset()isusedtocalculatetheoffsetoftherowtofetch,forthe selectedlinkpagenumber.Thegeneratedpaginationlinksrefertoalogicalpagenumber,notan SQLrownumber.Thismethodwillautomaticallycalculatetherequiredrowoffsetforyou,fromthe currentpagenumberandtheconfigureditemsperpagesetting.
$this->pagination->sql_offset(); // returns sql row offset as an integer
sql_limit()
Note:thismethodisdeprecatedinversion2.1use$thispaginationsql_limitproperty instead. $thispaginationsql_limit()isusedtoautomaticallygenerateSQLcode,withthe correctLIMITandOFFSETclausefortheselectedpagenumber.
echo $this->pagination->sql_limit(); // outputs the SQL below
LIMIT 3 OFFSET 6
Paginationclassproperties
Thefollowingpaginationclasspropertiesareavailableforuseinyourcontroller:
url current_page total_pages current_first_item current_last_item first_page last_page previous_page next_page sql_offset sql_limit
ExampleOne
$this->pagination = new Pagination(array( // 'base_url' => 'welcome/pagination_example/page/', // base_url will default to current uri 'uri_segment' => 'page', // pass a string as uri_segment to trigger former 'label' functionality 'total_items' => 254, // use db count query here of course 'items_per_page' => 10, // it may be handy to set defaults for stuff like this in config/pagination.php 'style' => 'classic' // pick one from: classic (default), digg, extended, punbb, or add your own! )); // Just echoing it is enough to display the links (__toString() rocks!) echo 'Classic style: '.$this->pagination; // You can also use the create_links() method and pick a style on the fly if you want echo '<hr />Digg style: '.$this->pagination->create_links('digg'); echo '<hr />Extended style: '.$this->pagination->create_links('extended'); echo '<hr />PunBB style: '.$this->pagination->create_links('punbb');
ExampleTwo
Excerptfromthecontrollermethod
public function page($page_no) { $content = new View('pages/items'); $items = new Items_Model; $content->items = $items->get_items($page_no, 10); // page to get starting at offset, number of items to get $this->pagination = new Pagination(array( 'base_url' => 'items/page/', // Set our base URL to controller 'items' and method 'page' 'uri_segment' => 'page', // Our URI will look something like http://domain/items/page/19 'total_items' => count($items->get_item_count()) // Total number of items. // Note that other config items are obtained from the pagination config file. )); $this->template->set(array( 'title' => 'Items', 'content' => $content ));
ExcerptfromtheView,showinghowtodisplaythelinks.
<h3>Items</h3> <?php echo $this->pagination->create_links() ?>
CreatingCustomizedPaginationStyles
ThedefaultKohanapaginationstylesarelocatedinthesystem/views/paginationdirectory. Tocustomizeanexistingstyleorcreateanewpaginationstyle,dothefollowing: 1. Createanewdirectorycalledapplication/views/pagination 2. Copyoneoftheexistingpaginationstylesfromsystem/views/pagination(e.g classic.php)toapplication/views/pagination 3. Youhavetheoptiontoeitherrenametheexistingpaginationstyletocreateacompletelynew style(e.g.custom.php)orkeepthesamenametooverrideoneofthedefaultstyles.
PaymentLibrary
Overview
Thepaymentlibraryallowsyoutoeasilyprocessecommercetransactionswithouthavingtoworry aboutallthebackenddetailsofconnectingandsettingupthecURLoptions.Ithasmanyfeatures: 1. 2. 3. 4. AnextremelyeasyAPI(onlyonemethodrequiredtoprocessatransaction!) Detailederrorreporting Extensiblewithbackenddriverstoconnecttomanydifferentpaymentgateways SupportforcreditcardgatewaysaswellasPayPallikegateways
Usingthelibraryisverysimple.Justsetthefieldsrequiredbyyourdriver,andprocess().
$payment = new Payment(); $payment->card_num = '1234567890123456'; $payment->exp_date = '0510'; if ($status = $payment->process() === TRUE) { // Report successful transaction } else { // $status has the error message, so display an error page based on it }
Configuration
Insystem/config/payment.phpthereisasampleconfigforeachpaymentgatewaywesupport. Simplycopythisfiletoyourapplicationdirectory,andremovethedriversyouarenotusing.The librarycansupportusingmorethanonedriverperapplicationbypassingthedrivernametothe constructor:
$paypal_payment = new Payment('Paypal'); $authorize_payment = new Payment('Authorize');
Afteryouremovethenonrequiredconfiglines,modifyyourdriverconfigasneeded.Usuallythis willincludesomesortofAPIusername/passwordcombination,butitdiffersforeachdriver.
Attributes
Thepaymentlibraryhasasetofdefaultattributesitusestosendpaymentstothegateway.These attributesarefairlyselfexplanatoryandarelistedbelow.
amount tax shipping first_name last_name company address city state zip email phone fax ship_to_first_name ship_to_last_name ship_to_company ship_to_address ship_to_city ship_to_state ship_to_zip
Specificdriversmayrequiresomeorallofthesefields.Theymayalsohavedriverspecificfields thatarenotedintheDriversection.
Methods
Thepaymentlibraryhasaminimalsetofmethodstouse:
set_fields()
Thismethodallowsyoutosetbulkpaymentattributeswithanarray.
$payment = new Payment(); $attributes = array ( 'card_num' = '1234567890123456', 'exp_date' = '0510' }; $payment->set_fields($attributes);
process()
Thismethoddoesthemagic.Afteryousetyourattributes,simplycallthismethodinaniftest.The methodreturnsTRUEonsuccessfulpaymenttransactionoranerrorstringonfailure.Itisuptoyou howtohandlethefailure.
Drivers
ThepaymentlibraryusesdriversmuchliketheDatabaselibrarydoesinordertokeeptheAPI consistentbetweenpaymentgateways.Itcurrentlysupportsthefollowinggateways:
1. 2. 3. 4. 5.
Authorize.net
RequiredFields 1. card_num 2. exp_date 3. amount
TridentGateway
RequiredFields 1. card_num 2. exp_date 3. amount
TrustCommerce
RequiredFields 1. card_num 2. exp_date 3. amount
YourPay.net
RequiredFields 1. 2. 3. 4. 5. 6. card_num exp_date amount tax shipping cvv
PayPal
RequiredFields 1. amount 2. payerid(afterpaypalauthentication) DriverSpecificDetails UsingthePayPaldriverisalittledifferentthananormalcreditcardtransaction.Itrequirestwo process()commandstoberun.ThefirstonewillsendtheusertoPayPaltoauthenticate,andthe secondonewillactuallyrunthetransaction.Belowisanexampleofthis.
class Paypal_Controller extends Controller { // This will demo a simple paypal transaction. It really only comes down to two steps. function __construct() { parent::__construct(); } login $this->paypal = new Payment();
// This will set up the transaction and redirect the user to paypal to function index() { $this->paypal->amount = 5; $this->paypal->process(); }
// Once the user logs in, paypal redirects them here (set in the config file), which processes the payment function return_test() { $this->paypal->amount = 5; $this->paypal->payerid = $this->input->get('payerid'); echo ($this->paypal->process()) ? "WORKED" : "FAILED"; } // This is the cancel URL (set from the config file) function cancel_test() { echo 'cancelled'; } // Just some utility functions. function reset_session() { $this->session->destroy(); url::redirect('paypal/index'); } function session_status() { echo '<pre>'.print_r($this->session->get(), true); }
WritingYourOwnDriver
TherearemanymorepaymentgatewaysthantherearedriversprovidedbyKohana.Weencourage youtowriteyourownwhenyouencounteragatewaynotsupportedbythelibrary.Aneasywayto doitislikeso: 1. Addanewentryinconfig/payment.phpwithyourdriverdetails.Usethepreviousentriesas anexample. 2. CopytheTridentGatewaydriverandrenameitto*GatewayName*.php 3. Altertherequiredfieldsarrayasinstructedinthegateway'sAPImanual(Youhavethis, right?;) 4. Modifythefieldsarraytoincludealltheavailablerelevantfieldsforthegateway 5. Modifytheconstructortosetdefaultvaluesfromtheconfigfile(APIusername/passwordfor example) 6. Modifytheset_fields()methodtodovariabletranslation(forexampleifyourgatewaynames cc_numsomethingdifferent.LookinyourAPImanualfordetails.) 7. Modifythe$post_urlternarystatementtoincludethecorrecttestandlivemodeAPIURLs 8. Modifyhowthereturnstatementhandlessuccessanderrorbasedonwhatthespecific gatewaystatusmessageis(LookinyouAPImanual)
ProfilerLibrary
TheProfileraddsusefulinformationtothebottomofthecurrentpagefordebuggingand optimizationpurposes.
Howtouse
Toenabletheprofileroutputonyourpagessimplyloadthelibrary:
$this->profiler = new Profiler;
Howtodisable
Theautomaticrenderingoftheoutputcanbedisabledwiththefollowingcode:
$this->profiler->disable()
Thisismostlyusefulwhenautoloadingtheprofilertodisabletheoutputforcertainpages.
Gettingtheoutput
Therenderedoutputmaybereturnedasastringatanytimeduringthepageexecutionbypassing TRUEasthefirstparameterinrender():
$output = $this->profiler->render(TRUE)
Note:Thiswillstopanybenchmarkscurrentlybeingrun.Onlybenchmarksandqueriesthathave beenrunupuntilthiscallwillbeshownintheoutput.
Configuretheprofiler
Editconfig/profiler.phptoconfigurewhichitems(post,cookie,session,database, benchmarks)theprofilerwillshow. Thischangeismadetoapplication/config/profiler.phpsoastoapplyonlytothe specificapplication.
/** * Show everything except database queries. (Other entries are default TRUE, read from system profiler config. */ $config['database'] = FALSE;
Acompleteprofiler.phpwouldlooklikethis
<?php defined('SYSPATH') or die('No direct script access.'); $config['post'] = FALSE; $config['cookie'] = FALSE; $config['session'] = FALSE; $config['database'] = FALSE; $config['benchmarks'] = TRUE;
RemembertosetatleastoneoftheitemstoTRUEotherwisetheprofilerwilldieinatraceerror.
SessionLibrary
Enablesapplicationstopersistuserstateacrosspages.
Whataresessions?
Sessionsenableyoutostoreandretrievedatabetweenrequestsonaperuserbasis.Typically,since eachwebpage(orAJAXrequest,etc)isanindividualrequest,thereisnowaytosetavariablein onerequestandgetit'svalueinanother.Sessionsareoneofseveralmechanismsthatexistto overcomethislimitation. Sessionsareusefulwhereasmallamountofdataneedstobepersistedacrossmostpagesandthat dataisspecifictotheparticularbrowsersession.Forexample,ifyourwebsitehasaloginpage, youmaywishtoremember,foronespecificwebbrowseronly,thataparticularuserhasloggedin. Ifyouwanttostoremoregeneraldatabetweenrequestsanditislessofanissuethatthedatabe
associatedwithonlyonebrowsersession,othermechanismsmaybemoreappropriate:
Kohana'sCachelibrary PHP'ssharedmemoryfacility
StartingaSession
ToloadtheSessionlibrary,addthefollowingcodetoyourcontrollerconstructor,ortoaparticular controllermethod:Addthecode:
$this->session = new Session;
Theabovelineofcodehastwoeffects:
Workingwithsessions
ThefollowingmethodsareavailableintheSessionlibrary:
create()
$thissessioncreate()canbecalledtocreateanewsession.Itwilldestroyanycurrent sessiondata. Notethatyoudonotneedtocallthismethodtoenablesessions.SimplyloadingtheSessionlibrary isenoughtocreateanewsession,orretrievedatafromanexistingsession.
id()
$thissessionid()retrievestheIDofthecurrentsession. Forexample,
echo 'Current session ID: ' . $this->session->id();
regenerate()
$thissessionregenerate()causesthesessionIDtoberegeneratedwhilstkeepingall thecurrentsessiondataintact. Note,thisisdoneautomaticallybytheframeworkafteranumberofrequestsforsecuritypurposes (setbythesession.regenerateconfigvalue).
destroy()
$thissessiondestroy()destroysallsessiondata,includingthebrowsercookiethatis usedtoidentifyit.
Workingwithsessiondata
TheSessionlibraryarrangesforPHP'sinbuiltsessionsarray,$_SESSION,tousethesession librariesdriver.Thismeansthataccessingsessiondatacanbedoneinthenormalway. Forexample,
// get some session data $data = $_SESSION['fish']; // set some session data $_SESSION['fish'] = 5;
Inadditiontothis,theSessionlibraryalsoprovidesit'sownmethodstodealwithsessiondata. Theseare:
get()
$thissessionget($key = FALSE, $default = FALSE)retrievesanamedvalue fromthesessiondata.
Forexample,
// returns value of foo. If it doesn't exist, returns the string 'bar' instead. $value = $this->session->get('foo','bar');
get_once()
$thissessionget_once($key)worksthesameasget()exceptthatitalsodeletesthe datafromthecurrentsessionafterwards. Forexample,
// returns value of foo and deletes foo from the session. $value = $this->session->get_once('foo');
set()
$thissessionset($keys, $val = FALSE)isusedtosetdatainthecurrentsession.
Forexample,
// set some_var to some_val $this->session->set('some_var', 'some_value'); // set several pieces of session data at once by passing an array to set() $this->session->set(array('fish' => 5, 'foo' => 'bar'));
del()
InKohana2.2del()hasbeenrenamedtodelete(). $thissessiondel($keys)isusedtodeleteapieceofdatafromthecurrentsession.
[mixed]$keysspecifiesthenameofthepieceofdatatodeletefromthesession.Itcanalso beanarrayofseveralkeystobedeleted.
Forexample,
// delete foo $this->session->del('foo'); // delete several pieces of data from the session by passing an array $this->session->del(array('bar', 'bas'));
"Flash"sessionData
Flashsessiondataisdatathatpersistsonlyuntilthenextrequest.Itcould,forexample,beusedto showamessagetoauseronlyonce. Aswithothersessiondata,youretrieveflashdatausing$thissessionget().
set_flash()
$thissessionset_flash($keys, $val = FALSE)setsflashdatainthecurrent session.
Forexample,
// set user_message flash session data $this->session->set_flash('user_message', 'Hello, how are you?'); // set several pieces of flash session data at once by passing an array $this->session->set_flash(array('user_message' => 'How are you?', 'fish' => 5));
keep_flash()
Usually,flashdataisautomaticallydeletedafterthenextrequest.Sometimesthisbehaviourisnot desired,though.Forexample,thenextrequestmightbeanAJAXrequestforsomedata.Inthiscase, youwouldn'twanttodeleteyouruser_messageintheexampleabovebecauseitwouldn'thave beenshowntotheuserbytheAJAXrequest. $thissessionkeep_flash($keys)canbeusedtokeepflashsessiondataforonemore request(akafresheningflashdata).
[string]$keysspecifiesthename(s)oftheflashsessionvariablestokeep.
// Don't delete the user_message this request $this->session->keep_flash('user_message'); // Don't delete messages 1-3
Ifyoudon'tsupplyanyargumentstothefunctionallcurrentflashsessionvariableswillbe freshened.
// Don't delete any flash variable $this->session->keep_flash();
FresheningmultipleorallflashsessionvariablesisKohana2.2functionality.
ConfiguringaSession
Edittheconfigfileapplication/config/session.php
/* * File: Session * * Options: * driver - Session driver name: 'cookie','database' or 'native' * storage - Session storage parameter, used by drivers * name - Default session name * validate - Session parameters to validate * encryption - Encryption key, set to FALSE to disable session encryption * expiration - Number of seconds that each session will last (set to 0 for session which expires on browser exit) * regenerate - Number of page loads before the session is regenerated (set to 0 for NO automatic regeneration) * gc_probability - Percentage probability that garbage collection will be executed */ $config = array ( 'driver' => 'cookie', 'storage' => '', 'name' => 'kohanasession', 'validate' => array('user_agent'), 'encryption' => FALSE, 'expiration' => 7200, 'regenerate' => 3, 'gc_probability' => 2 );
SessionStorage
Bydefaultsessiondataisstoredinacookie.Youcanchangethisinthefile config/session.php.Thedrivercanbesetto'cookie','database'or'native'.Sessionnameand otherconfigurationoptionscanalsobesethere. UsingaDatabase Thestoragesettinginconfig/session.phpmustbesettothenameofthedatabasetable. Optionallyyoucanaddagroupinconfig/database.phpusingthesamename,ifthisisnot founditwillusethedefault. Tableschema
CREATE TABLE `kohana_session` ( `session_id` varchar(40) NOT NULL,
`last_activity` int(10) UNSIGNED NOT NULL, `data` text NOT NULL, PRIMARY KEY (`session_id`) )
Lifetimedoesnotneedtobesetasitisoverriddenbythesessionexpirationsetting.
Instance
Toretrievetheinstantiatedsessionlibraryyoucanusetheinstance()method.Ifnoinstanceis availableonewillbecreated.
$session=Session::instance(); $var = $session->get('session_item);
Sessioninstancemethodscanbecalleddirectly.
$var = Session::instance()->get('session_item'); Session::instance()->set('session_item', 'item value');
URILibrary
TheURIclassprovidesthemethodsforworkingwithURI'sandURIsegments.Ifyouuseroutingit alsohasmethodstoworkwithreroutedURI's. Note: ThislibraryisinitializedautomaticallybyKohana.Noneedtodoityourself
Methods
segment()
segment($index = 1, $default = FALSE)retrievesaspecificURIsegment.Returns $defaultwhenthesegmentdoesnotexist.
//url: http://www.example.com/index.php/article/paris/hilton/
3. hilton
echo $this->uri->segment(3); // Returns 'hilton' echo $this->uri->segment(4, 'spears'); // Returns 'spears'
Note:thismethodalsoacceptsstrings.Whenastringisgivenasfirstargument,itwillreturnthe segmentfollowingthestring.
echo $this->uri->segment('article'); // Returns 'paris' echo $this->uri->segment('paris'); // Returns 'hilton' echo $this->uri->segment('hilton'); // Returns FALSE
rsegment()
Identicaltosegment()exceptthatitusesthereroutedURItoretrievethesegmentsfrom.
segment_array()
segment_array($offset,$associative)returnsanarrayofalltheURIsegments
total_segments()
total_segments()returnsthenumberofsegments
echo $this->uri->total_segments(); //returns 3
string()
string()returnstheentireURIasastring
echo $this->uri->string(); // returns: article/paris/hilton/
last_segment()
last_segment()returnsthelastsegmentofanURI
echo $this->uri->last_segment(); // returns: hilton
argument()
argument()returnstherequestedarguments.Thisdiffersfromsegmentsasitwillonlylookat theargumentsgivenandskipthecontrollerandmethodsegment.
echo $this->uri->argument(1); // returns: hilton
argument_array()
argument_array()returnsanarraycontainingallarguments
echo $this->uri->argument_array(); // returns: array( 'hilton' )
total_arguments()
total_arguments()returnsthetotalnumberofarguments.
echo $this->uri->total_arguments(); // returns: 1
build_array()
Thismethodonlyexistsinversion2.2
UserAgentLibrary
ThislibraryisdeprecatedandwillnolongerbeavailableinKohana2.2.It'sfunctionalitywillmove totheKohanacoreclass.
Loadingthelibrary
$this->user_agent = new User_agent;
Itcanthenbeaccessedthrough$thisuser_agent.Allmethodsinthislibraryrelyondataprovided bythevisitor'swebbrowser,soitcouldbefaked.
Methods
is_browser()
Checksifthecurrentrequestisbeingmadebyawebbrowser,andreturnsTRUEifthisisthecase.
if ($this->User_agent->is_browser() == TRUE) { echo 'Hello browser!'; }
is_robot()
Checksifthecurrentrequestisbeginmadebyarobot(e.g.asearchenginespider),andreturns TRUEifthisisthecase.
if ($this->User_agent->is_robot() == TRUE) { echo 'Hello robot!'; }
is_mobile()
Checksifthecurrentrequestisbeginmadebyamobilebrowser(e.g.PocketIEorOperamini),and returnsTRUEifthisisthecase.
if ($this->User_agent->is_mobile() == TRUE) { echo 'Hello mobile!'; }
accept_lang()
TheAcceptLanguageheaderspecifiesinwhichlanguagethevisitorwouldlikehisrequesttobe returned.Theaccept_langcheckstheAcceptLanguageheaderforthespecifiedlanguage,and returnsTRUEifthislanguageisintheAcceptLanguageHeader,anfalseifthisisnotthecase.
[string]Languagetocheckfordefault='en'
if ($this->User_agent->accept_lang('nl') == TRUE) { // Send result in Dutch if accepted echo 'Hallo wereld!'; } else { // Send result in English echo 'Hello world!'; }
accept_charset()
TheAcceptCharsetheaderspecifiesthevisitor'sacceptedcharsets.Theaccept_charset functionchecksifthespecifiedcharsetisfoundinthisheader,andreturnsTRUEifitis,and FALSEifitisn't.
[string]Charsettocheckfordefault=utf8
if ($this->User_agent->accept_charset('utf-8') == TRUE) { echo 'I\'m glad you accept UTF-8 charset!'; } else { echo 'Please start supporting UTF-8'; }
Properties
browser
Containsthenameofthebrowser.
// Prints name of the browser on screen (e.g. 'Firefox' or 'Internet Explorer') print Kohana::debug($this->User_agent->browser);
agent
Containsthecompleteuseragentstring.
print Kohana::debug($this->User_agent->agent);
ItcouldresultinHTMLas:
Mozilla/5.0 (Windows; U; Windows NT 6.0; nl; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11
mobile
Containsthenameofthemobilebrowser,iftherequesthasbeenmadebyamobiledevice.
print Kohana::debug($this->User_agent->mobile);
ItcouldresultinHTMLas:
Opera Mini
version
Containsthebrowserversion.
print Kohana::debug($this->User_agent->version);
ItcouldresultinHTMLas:
2.0.0.11
referrer
Containstherefererstring.
print Kohana::debug($this->User_agent->referer);
ValidationLibrary
Ifyou'researchingforsomepremadevalidationfunctions,checkthevalidationhelper. ThislibrarywillseesignificantAPIchangesinKohana2.2 AnewvalidationlibrarywillbereleasedinKohana2.2.Itisavailableinthesubversionrepository andisacompleterewriteofthecurrentlibrary. Informationonitssyntax:http://learn.kohanaphp.com/2008/02/23/apeekatkohanasnew validationlibrary/
Gettingstarted
LoadtheLibrary
Inthecodebelow,$somearrayisanarraypassedtothevalidationclassforapproval.Itcansimply be$_POSTifyoudesire,butyou'llprobablywanttohandlethisdifferently.That'suptoyou.
$validation = new Validation($somearray);
SetuptheRules
Therulesaresetupasanassociativearrayofarrays.Theassociativearrayhasseveralkeysgiventhe nameofafieldassignedintheHTMLoftheform.Theassociatedvalueisanarraywith2records. Thefriendlyname,thefirstrecord,isthenameyou'dliketobeusedintheerrormessage.This probablyshouldbethesameoneyoucalleditwhentellingtheuserwhattoputinthatfield.The
secondpartisthevalidationrules.Rulesareapipedelimitedseriesofmethodsthatareappliedto thestring.
$validation->set_rules(array( // Format: // key friendly name, validation rules 'FirstName' => array('First Name', '=trim|required[2,30]'), 'LastName' => array('Last Name','=trim|required[2,30]'), 'Email' => array('Email Address','=trim|required[5,50]|valid_email_rfc'), ));
ValidatingInput
Runthevalidation
Use
$validation->run();
torunthecomparisonofyour$arraythatyoupassedwhenyouinitializedthevalidation.Thiswill returntrueifthearrayhadnovalidationerrorsinit.Itwillreturnfalseiftherewasanissue.
ReporttheErrors
Usethecode
$validation->error_string;
Noticethatthestring{message}isreplacedbytheactualerrormessage.Ifyouwantedtosimply addahorizontalruleaftereachoneyoucouldcodethatlikethis:
$validation->error_format("{message}<hr/>");
CompleteExampleCode
$validation = new Validation($_POST); if ( ! empty($_POST)) { $validation->set_rules(array ( // Format: // key friendly name, validation rules 'FirstName' => array('First Name', '=trim|required[2,30]'), 'LastName' => array('Last Name', '=trim|required[2,30]'), 'Email' => array('Email Address', '=trim|required[5,50]| valid_email_rfc'), )); if ($validation->run())
$validation->error_format("<li>{message}</li>"); ?> <p>Your form failed validation. Please review the following issues with your form and resubmit it.</p> <ul> <?php echo $validation->error_string ?> </ul> <?php } }
set_message()
Allowscustomizationoftheerrormessagethatisdisplayeduponfailedvalidationforaspecific function.Note:Thekeynamehastomatchthefunctionnamethatitcorrespondsto.Thisisvery usefulwhenutilizingcustomcallbackvalidationfunctions.
public function _tester($value) { $this->validation->set_message(__FUNCTION__, 'omg callback error'); $this->validation->add_error(__FUNCTION__, 'one'); }
UsingPHPfunctionsonfields
Precedetherulewith=. E.g.
array('First Name', '=trim|required[2,30]');
Usingyourowncustomcallbacks
Precedetherulewithcallback_ Example
array('First Name', 'callback_valid_password|required[2,30]'); //will effectively call $this->validation->valid_password($data);
Rules
Rule required Parameter Yes Description Example required[1,30]sameasrequired| ReturnFALSEifformfieldis min_length[1]|max_length[30]or empty,orlengthvalueisoutof required[30]sameasrequired| rangeparameters exact_length[30]
min_length Yes max_length Yes exact_length Yes valid_email_ No rfc valid_email No valid_url valid_ip alpha utf8_alpha alpha_nume ric utf8_alpha_ numeric alpha_dash utf8_alpha_ dash digit utf8_digit numeric No regex No depends_on Yes range No Yes No Yes
ReturnFALSEiflengthfield valueislessthanparameter ReturnFALSEiflengthfield valueisgreaterthanparameter ReturnFALSEiflengthfield valueisnotsameasparameter ReturnFALSEifemailisnot rfc822valid ReturnFALSEifemailisnot valid ReturnFALSEifurlisnotvalid ReturnFALSEifipisnotvalid ReturnFALSEifformfield doesnotconsistonlyof alphabeticalcharacters ReturnFALSEifformfield doesnotconsistonlyof alphabeticalornumeric characters
depends_on[field_name]
Variableprepping
Name Parameter Description prep_for_form prep_for_url strip_image_tags xss_clean encode_php_tags
Helpers
ArrayHelper
TheArrayhelperassistsintransformingarraysviatherotate()andremove()methods.
Methods
rotate()
'rotate'rotatesanarray(twodimensional)matrix.Thetwoargumentsare:
[array]Thearrayyouwanttorotate [boolean]Doyouwanttokeepthesamekeysintherotatedarray?TRUEbydefault
Example:
// Please note that the print() statements are for display only $optical_discs = array ( 'CD' => array('700', '780'), 'DVD' => array('4700','650'), 'BD' => array('25000','405') ); print Kohana::debug($optical_discs); $optical_discs = arr::rotate($optical_discs, FALSE); print ('<br /><br />'); print Kohana::debug($optical_discs);
ItwillresultinHTMLas:
Array ( [CD] => Array ( [0] => 700 [1] => 780 ) [DVD] => Array ( [0] => 4700 [1] => 650 ) [BD] => Array ( [0] => 25000 [1] => 405 ) ) Array ( [0] => Array ( [CD] => 700 [DVD] => 4700
[BD] => 25000 ) [1] => Array ( [CD] => 780 [DVD] => 650 [BD] => 405 ) )
remove()
'remove'removesakeyfromanarrayandreturnsit. Thetwoargumentsare:
[string]Thekeyyouwantremovedfromanarray [array]Thearrayyouwantthekeytoberemovedfrom
Example:
// Please note that the print() statements are for display only $optical_discs = array ( 'CD' => array('700', '780'), 'DVD' => array('4700','650'), 'BD' => array('25000','405') ); print Kohana::debug($optical_discs); $cd = arr::remove('CD', $optical_discs); print ('<br />'); print Kohana::debug($cd); print ('<br />'); print Kohana::debug($optical_discs);
ItwillresultinHTMLas:
Array ( [CD] => Array ( [0] => 700 [1] => 780 ) [DVD] => Array ( [0] => 4700 [1] => 650 ) [BD] => Array ( [0] => 25000 [1] => 405 ) )
Array ( [0] => 700 [1] => 780 ) Array ( [DVD] => Array ( [0] => 4700 [1] => 650 ) [BD] => Array ( [0] => 25000 [1] => 405 ) )
binary_search()
'binary_search'performsabasicbinarysearchonanarray.Bydefault,itreturnsthekeyofthearray valueitfinds.Thefourargumentsare:
Example:
$my_array = array('10', '20', '30', '50', '80'); echo arr::binary_search('50', $my_array); // 3 echo arr::binary_search('45', $my_array); // FALSE (not found) echo arr::binary_search('45', $my_array, TRUE); // 3 echo arr::binary_search('35', $my_array, TRUE); // 2
range()
CookieHelper
ProvidesmethodsforworkingwithCOOKIEdata.
Configuration
Defaultsettingsforcookiesarespecifiedinapplication/config/cookie.php.Youmay overridethesesettingsbypassingparameterstothehelper. 1. prefix:Aprefixmaybesettoavoidnamecollisions.Defaultis''. 2. domain:Avaliddomain,forwhichthecookiemaybewritten.Defaultis''(Useon localhost).Forsitewidecookies,prefixyourdomainwithaperiod.example.com 3. path:Avalidpathforwhichthecookiemaybewritten.Defaultistherootdirectory'/' 4. expire:Thecookielifetime.Setthenumberofsecondsthecookieshouldpersist,until expiredbythebrowser,startingfromwhenthecookieisset.Note:Setto0(zero)seconds foracookiewhichexpireswhenthebrowserisclosed. 5. secure:Thecookiewillonlybeallowedoverasecuretransferprotocol(HTTPS).Defaultis FALSE. 6. httponly:ThecookiecanbeaccessedviaHTTPonly,andnotviaclientscripts.Defaultis FALSE.Note:RequiresatleastPHPversion5.2.0
Methods
set()
cookie::set()acceptsmultipleparameters,onlythecookienameandvaluearerequired.You maypassparameterstothismethodasdiscretevalues:
cookie::set($name, $value, $expire, $path, $domain, $secure, $httponly, $prefix);
Oryoumaypassanassociativearrayofvaluesasaparameter:
$cookie_params = array( 'name' => 'Very_Important_Cookie', 'value' => 'Choclate Flavoured Mint Delight', 'expire' => '86500', 'domain' => '.example.com', 'path' => '/', 'prefix' => 'one_', ); cookie::set($cookie_params);
get()
cookie::get()acceptsmultipleparameters,Onlythecookienameisrequired.
$cookie_value = cookie::get($cookie_name, $prefix, $xss_clean = FALSE);
SettingthethirdparametertoTRUEwillfilterthecookieforunsafedata. ReturnsFALSEifthecookieitemdoesnotexist.
delete()
cookie::delete()acceptsmultipleparameters,Onlythecookienameisrequired.This methodisidenticalcookie::set()butsetsthecookievalueto''effectivelydeletingit.
cookie::delete('stale_cookie');
DateHelper
TheDatehelperassistsinformatingdatesandtimesallowingforadditionandconversionbetween differentformats.
Methods
unix2dos()
'unix2dos'convertsUNIXtimeintoDOStimeTheoneargumentsis:
[int]UNIXtimestamp
Example:
// Please note that the print() statements are for display purposes only $time = mktime(0, 0, 0, 31, 10, 1987); print ($time); $time = date::unix2dos($time); print ($time);
ItwillresultinHTMLas:
616046400 317325312
dos2unix()
'dos2unix'convertsDOStimeintoUNIXtimeTheoneargumentsis:
[int]DOStimestamp
Example:
// Please note that the print() statements are for display purposes only $time = 317325312; print ($time); $time = date::dos2unix($time); print ($time);
ItwillresultinHTMLas:
317325312 616046400
offset()
'offset'calculatesthesecondsbetweentwotimezonesThetwoargumentsare:
[int]remotetimezone [mixed]uselocaltime?defaultisTRUEelseenteryourown
Example:
// Please note that the print() statements are for display purposes only // This example was executed in the EST timezone print (date::offset('CST').'<br />'); print (date::offset('CST', 'MST').'<br />'); print (date::offset('UTC', 'GMT').'<br />');
ItwillresultinHTMLas:
-3600 3600 0
seconds()
'seconds'createsanarrayofnumbersbasedonyourinputThethreeargumentsare:
Example:
// Please note that the print() statements are for display purposes only print Kohana::debug(date::seconds()); print Kohana::debug(date::seconds(2,1,7)); print Kohana::debug(date::seconds(100,200,400));
ItwillresultinHTMLas:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23 [24] => 24 [25] => 25 [26] => 26 [27] => 27 [28] => 28 [29] => 29
[30] [31] [32] [33] [34] [35] [36] [37] [38] [39] [40] [41] [42] [43] [44] [45] [46] [47] [48] [49] [50] [51] [52] [53] [54] [55] [56] [57] [58] [59]
=> => => => => => => => => => => => => => => => => => => => => => => => => => => => => =>
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
Array ( [1] => 1 [3] => 3 [5] => 5 ) Array ( [200] => 200 [300] => 300 )
minutes()
Pleaseseeseconds.
hours()
'hours'countsthenumberofhoursthereareleftinadayorfromaspecificstartpointThethree argumentsare:
Example:
// Please note that the print() statements are for display purposes only // This example ran at 6:10PM EST print Kohana::debug(date::hours()); print Kohana::debug(date::hours(1, TRUE, 9)); print Kohana::debug(date::hours(1, TRUE, 22)); print Kohana::debug(date::hours(1, TRUE, date('g'))); // 24-hour format of an hour without leading zeros
ItwillresultinHTMLas:
Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 ) Array ( [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23 ) Array ( [22] => 22 [23] => 23 ) Array ( [18] [19] [20] [21] [22] [23] )
18 19 20 21 22 23
ampm()
'ampm'calculateswhetherthesuppliedintegermakesthehourAMorPMTheoneargumentis:
[int]hourtocalculate
Example:
// Please note that the print() statements are for display only // This example ran at 5:45PM EST print Kohana::debug(date::ampm(1)); print Kohana::debug(date::ampm(13)); print Kohana::debug(date::ampm(date('G'))); // 24-hour format of an hour without leading zeros
ItwillresultinHTMLas:
AM PM PM
days()
'days'countsthenumberofdaysthereareinaspecificmonthofaspecificyearThetwoarguments are:
[int]month(112) [int]yeardefault:currentyear
Example:
// Please note that the print() statement is for display purposes only print Kohana::debug(date::days(5,2007));
ItwillresultinHTMLas:
Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 [18] => 18 [19] => 19 [20] => 20 [21] => 21 [22] => 22 [23] => 23
24 25 26 27 28 29 30 31
months()
'months'returnsanmirroredarraywiththemonthnumbersoftheyear. Example:
// Please note that the print() statement is for display purposes only print Kohana::debug(date::months());
ItwillresultinHTMLas:
Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 )
years()
'years'returnsanarraywiththeyearsbetweenthespecifiedyears.Thetwoargumentsare:
[int]startyeardefault=currentyear5 [int]endyeardefault=currentyear+5
Example:
// Please note that the print() statements are for display purposes only // This example ran in 2007 print Kohana::debug(date::years()); print Kohana::debug(date::years(1998,2002));
ItwillresultinHTMLas:
Array ( [2002] [2003] [2004] [2005] [2006] => => => => => 2002 2003 2004 2005 2006
timespan()
'timespan'returnsthetimebetweentwotimestampsinahumanreadableformatTheargumentsare:
Example:
// Please note that the print() statements are for display purposes only // This example ran in 2007 $timestamp = time() - (60*60*24*7*31*3); // timestamp of 651 days ago $timestamp2 = time() - (60*60*24*7*50); // timestamp of 350 days ago print Kohana::debug(date::timespan($timestamp)); print Kohana::debug(date::timespan($timestamp, time(), 'years,days')); print Kohana::debug(date::timespan($timestamp, $timestamp2)); print 'minutes: '.Kohana::debug(date::timespan($timestamp, time(), 'minutes'));
ItwillresultinHTMLas:
Array ( [years] => 1 [months] => 9 [weeks] => 2 [days] => 2 [hours] => 0 [minutes] => 0 [seconds] => 0 ) Array ( [years] => 1 [days] => 286 ) Array ( [years] => 0 [months] => 10 [weeks] => 0 [days] => 1
adjust()
'adjust'convertsanhourintegerinto24hourformatfromanon24hourformat.Thetwoarguments are:
[int]hourinnon24hourformat [string]AMorPM
Example:
// Please note that the print() statements are for display only print Kohana::debug(date::adjust(11, 'PM'));
ItwillresultinHTMLas:
23
DownloadHelper
Thedownloadhelperassistsinforcingdownloadingoffilesbypresentinguserswiththesaveas dialog.
Methods
force()
'force'forcesadownloadofafiletotheuser'sbrowser.Thisfunctionisbinarysafeandwillwork withanyMIMEtypethatKohanaisawareof.
$filename[string]filenameofthefiletobedownloadeddefault= $data[string]datatobesentifthefilenamedoesnotexistsdefault=
Example:
// File path is relative to the front controller download::force("file.txt"); // For a file located in application/downloads // Use relative path download::force('./application/downloads/file.txt'); // OR use the defined application path download::force(APPPATH.'downloads/file.txt');
EmailHelper
AnEmailhelpertoworkwiththeSwiftemaillibrary.
Configuration
Theswiftmailerconfigurationforthishelperisfoundinconfig/email.php Insidetheconfig/email.phpfileyoucanselectthedrivertypewhicharenative, sendmail, smtp Example:usingsmtp
$config['driver'] = 'smtp'; $config['options'] = array('hostname'=>'yourhostname', 'username'=>'yourusername', 'password'=>'yourpassword', 'port'=>'25');
Methods
connect() send()
'send'sendsanemailusingthespecifiedinformation.Theparametersare:
Example:
$to 'Name') $from $subject $message = 'from@example.com'; = 'This is an example subject'; = 'This is an <strong>example</strong> message';
ExpiresHelper
Providesmethodsformanagingbrowserawarepagecaching.Moreinformationonclientsidepage cachingcanbefoundatcachingphpperformance AllowssettingapagecachetimebysendingLastModifiedandExpiresheadersforthepage. Allowscheckingifthepageisolderthanthepagecachetime.Ifso,thepageisexpiredandanew pagemustbeouput.Ifnot,a304notmodifiedstatusheaderandNOdataissent.Thepageis retrievedbythebrowserfromit'sowncache.
Methods
set()
expires::set()Setsanexpirytimeforalocal,browserpagecache.Thesingleparameteris:
[integer]Thetime,inseconds,untilpageexpires.Defaultis60seconds.
Example
expires::set(300);
check()
expires::check()Determinesifacachedpageneedstoberefreshed.Thesingleparameteris. *[integer]Thetimeinseconds,toaddtothelastmodifiedtime.Defaultis60seconds. Example
if (expires::check(300) === FALSE)
check_headers()
expires::check_headers()Hasnoparameters.Calledinternallybyexpires::set() ReturnsbooleanTRUEifaLastModifiedorExpiresheaderhasNOTbeensent. Example
if (expires::check_headers()) echo 'Safe to send Expires header';
prevent_output()
expires::prevent_output()Hasnoparameters.Calledinternallyby expires::check()Youwouldnotnormallycallthisfunctiondirectly,asitclearstheKohana outputbuffer. Example
expires::prevent_output() // will set Kohana::$output = '';
FullExample
Thecontrolleroutputsapagefromasinglemethod.Theobjectiveistocachethepageforten seconds.Ifthepageisreloadedwithintenseconds,thecachedpagedatashouldbedisplayed. Controller:
<?php defined('SYSPATH') or die('No direct script access.'); /** * Default Kohana controller. */ class Welcome_Controller extends Controller { public function index() {
if (expires::check(10) === FALSE) expires::set(10); $welcome = new View('welcome'); // We should only see the time updated in the view after 10 seconds // note, it is not this data that is cached, but the browser that fetches a locally cached page $welcome->now = date(DATE_RFC822); $welcome->render(TRUE); } }
View:
<h2>Welcome!</h2> <p>It is now <?php echo $now ?></p> <hr/>
FeedHelper
TheFeedhelperassistintheparsingofremoteRSSfeeds.
Methods
parse()
'parse'parsesaRSSfeedandreturnstheparsedfeedasanarray.
[string]remotefeedurl,orlocalfilepath [int]maximumamountofitemstoparsedefault=0(infinite)
UsethecodeaboveonthisRSSfeed:
<?xml version="1.0" encoding="UTF-8"?> <rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"> <channel> <item> <title>Some feed item</title> <link>http://www.example.com/article34</link> <description>This article is really cool!</description> <author>Aart-Jan Boor</author> <pubDate>Sat, 08 Dec 2007 13:28:11 GMT</pubDate> </item> <item> <title>Some feed item2</title> <link>http://www.example.com/article546</link> <description>This article is really cool too!</description> <author>Aart-Jan Boor</author> <pubDate>Sat, 08 Dec 2007 12:57:56 GMT</pubDate> </item>
<item> <title>Some feed item3</title> <link>http://www.example.com/article4523</link> <description>This article is the best!</description> <author>Aart-Jan Boor</author> <pubDate>Sat, 08 Dec 2007 12:39:42 GMT</pubDate>
ItwillresultinHTMLas:
Array ( [0] => Array ( [title] => Some feed item [link] => http://www.example.com/article34 [description] => This article is really cool! [author] => Aart-Jan Boor [pubDate] => Sat, 08 Dec 2007 13:28:11 GMT ) [1] => Array ( [title] => Some feed item2 [link] => http://www.example.com/article546 [description] => This article is really cool too! [author] => Aart-Jan Boor [pubDate] => Sat, 08 Dec 2007 12:57:56 GMT ) [2] => Array ( [title] => Some feed item3 [link] => http://www.example.com/article4523 [description] => This article is the best! [author] => Aart-Jan Boor [pubDate] => Sat, 08 Dec 2007 12:39:42 GMT ) )
FileHelper
Ahelperdesignedtomanipulatefilesandfilenames.
Methods
extension()
'extension'runsaregularexpressioncheck,returningtheentirestringafterthelastperiod(.)also knownasthefileextensionTheparametersare:
param:[string]filenametocheckextensionof return:[string]entirestringafterlastperiod(.)
Example:
echo file::extension('/etc/apache2/apache2.conf'); conf
mime()
'mime'findstheMIMEtypeofafilefirstbyusingPHP'sbuiltindatabaseandthenKohana's MIMEconfigurationfile(system/config/mimes.php).Theparametersare:
param:[string]filenametocheckMIMEtypeof return:[mixed]stringiffound,FALSEifnotfound
Example:
$file = 'my_movie.ogg' echo $file.' ('.file::mime($file).')'; my_movie.ogg (application/ogg)
split()
'split'splitsafileintopiecesmatchingaspecificsizeindicatedinmegabytes.Theparametersare:
Example:
$file = 'humpty_dumpty.mp3'; // pretend it is 7.8 MB large echo (file_exists($file)) ? file::split($file,FALSE,2) : 'can not find file!' ; 4
Directorylisting:
-rwxrwxrwx -rw-r--r--rw-r--r--rw-r--r--rw-r--r-1 1 1 1 1 www-data www-data www-data www-data www-data www-data www-data www-data www-data www-data 8186302 2097152 2097152 2097152 1894846 2008-05-06 2008-05-06 2008-05-06 2008-05-06 2008-05-06 20:11 20:15 20:15 20:15 20:15 humpty_dumpty.mp3 humpty_dumpty.mp3.001 humpty_dumpty.mp3.002 humpty_dumpty.mp3.003 humpty_dumpty.mp3.004
join()
'join'joinssplitedfiles(possiblybyfile::split()),assuminga.###extension.Theparametersare:
Example:
$file_in = 'humpty_dumpty.mp3'; // from our last example $file_out = 'humpty_dumpty-back_together_again.mp3'; // output name echo file::join($file_in,$file_out);
Directorylisting:
-rwxrwxrwx 1 www-data www-data -rw-r--r-- 1 www-data www-data -rw-r--r-- 1 www-data www-data -rw-r--r-- 1 www-data www-data -rw-r--r-- 1 www-data www-data -rw-r--r-- 1 www-data www-data back_together_again.mp3 8186302 2097152 2097152 2097152 1894846 8186302 2008-05-06 2008-05-06 2008-05-06 2008-05-06 2008-05-06 2008-05-06 20:11 20:15 20:15 20:15 20:15 20:17 humpty_dumpty.mp3 humpty_dumpty.mp3.001 humpty_dumpty.mp3.002 humpty_dumpty.mp3.003 humpty_dumpty.mp3.004 humpty_dumpty-
FormHelper
TheFormhelperprovidesmethodstoassistyouincreatingforms.Itdoesnotdovalidationor filtering.Ifyouwanttogenerateyourformswithvalidationandfilteringyoucandosowiththe Forgelibrary
GettingStarted
You'llneedtousealinelikethistobegintheform.
print form::open(string $submit, array $attr, array $hidden );
AddingFields
YoumayaddformfieldsasyouwouldinstraightHTML,buttheoptionexiststocreatethemusing php.Herearesomeexamples.
print form::dropdown($data, $options, $selected) print form::textarea($data) print form::input($data)
Methods
open()
Inordertoopentheform,yousimplyneedto:Thisusesthedefaultvalues,usingPOSTtosubmit theformtothecurrentpage.
print form::open()
Toaddattributes:
// Submits the page to: domain.tld/products/search.html // CSS class 'search_form' is applied print form::open('products/search', array('class'=>'search_form'));
// Stay on the current page, and add a hidden input field named 'type' with value: 'product' print form::open('', array(), array('type'=>'product')); // Sending a form to the current page using GET print form::open('', array('method'=>'get'));
open_multipart()
OpensaformforsubmittingbinarydataviaPOST.Youmustspecifyanencodingtypeattributeof 'multipart/formdata'. Examples:
// Submits multipart form data to the current page print form::open('', array('enctype' => 'multipart/form-data'));
ResultsinHTML
<form action="http://localhost/index.php/welcome" enctype="multipart/form-data" method="post">
input()
CreatesanHTMLforminputtag.Defaultstoatexttype.Theparametersare:
Example:
print form::input('field_name', 'field_value', ' style="text-align: right;"');
ResultinHTML:
<input type="text" id="field_name" name="field_name" value="field_value" style="text-align: right;" />
It'snotnecessarytouseallparameters. Example:
print print print name, form::input(); // don't use parameters form::input('field_name'); // use only 1 parametr - for name and id form::input('field_name', 'field_value'); // use only 2 parameters - for id and value
ResultinHTML:
<input type="text" id="" name="" value="" /> <input type="text" id="field_name" name="field_name" value="" /> <input type="text" id="field_name" name="field_name" value="field_value" />
hidden()
'hidden'generatesahiddenformfield.Theparametersare:
[string]/[array]dataforkeyattributes
[string]valueofthefielddefault=
Example:
// Please note that the print() statements are for display purposes only print Kohana::debug(form::hidden("fieldName","fieldValue")); $array=array('field1'=>'value1','field2'=>'value2'); print Kohana::debug(form::hidden($array));
ItwillresultinHTMLas:
<input type="hidden" id="fieldName" name="fieldName" value="fieldValue" /> <input type="hidden" id="field1" name="field1" value="value1" /> <input type="hidden" id="field2" name="field2" value="value2" />
password()
'password'generatesapasswordformfield.Theparametersare:
Example:
// Please note that the print() statements are for display purposes only print Kohana::debug(form::password("fieldName","fieldValue")); print Kohana::debug(form::password("fieldName","fieldValue",' id="fieldId"')); $array=array('name'=>'fieldName','value'=>'fieldValue','id'=>'fieldId','class'=> 'formField'); print Kohana::debug(form::password($array));
ItwillresultinHTMLas:
<input type="password" id="fieldName" name="fieldName" value="fieldValue" /> <input type="password" id="fieldName" name="fieldName" value="fieldValue"id="fieldId" /> <input type="password" id="fieldId" name="fieldName" value="fieldValue" class="formField" />
upload()
GenerateHTMLforminputtagtypefileforuploadfiles: Theparametersare:
Example
$attributes = array('name' => 'file_1', 'class' => 'your-class'); echo form::upload($attributes, 'path/to/local/file')
ResultinHTML:
textarea()
CreatesanHTMLformtextareatag.
print form::textarea(string/array $data, string $value)
Theparametersare:
[string]/[array]textareanameoranarrayofHTMLattributes [string]textareavalue,whenusinganame
Example
print form::textarea('field_name', 'field_value');
ResultinHTML:
<textarea name="field_name">field_value</textarea>
Wecanalsousearrayforthefirstparameter.Lookatthisexample:
print form::textarea(array('name' => 'field_name', 'value' => 'field_value', 'class' => 'our_class'));
ResultinHTML:
<textarea name="field_name" class="our_class">field_value</textarea>
dropdown()
Createsadropdownselectionbox.Theparametersare:
Example:
$selection = array('basic' =>'Basic', 'standard' => 'Standard', 'custom' => 'Custom'); // The 'standard' option will be the default selection print form::dropdown('input_dropdown',$selection,'standard');
ResultsinHTML
<select id="input_dropdown" name="input_dropdown"> <option value="basic">Basic</option> <option value="standard" selected="selected">Standard</option> <option value="custom">Custom</option> </select>
checkbox()
Createsa'tickbox'typeselectionbox.
Theparametersare:
Example:
print print print print
ResultsinHTML
<label for="check_spam_box">Always send me Spam (Opt in): </label> <input type="checkbox" id="check_spam_box" name="check_spam_box" value="send_spam" /> <label for="check_money_box">Never send me Money (Opt out): </label> <input type="checkbox" id="check_money_box" name="check_money_box" value="send_no_money" checked="checked" />
Browseroutput: AlwayssendmeSpam(Optin):NeversendmeMoney(Optout):
radio()
Generatesa'radio'typeselectionbox,similartocheckbox,butallowsforeasiermultipleselections. Theparametersare:
Example:
print print print print print print
ResultsinHTML
<label for="radio_cute_box">I am cute: </label> <input type="radio" id="radio_cute_box" name="radio_cute_box" value="is_cute" / ><br /> <label for="radio_single_box">I am single: </label> <input type="radio" id="radio_single_box" name="radio_single_box" value="is_single" checked="checked" /><br /> <label for="radio_rich_box">I am rich: </label> <input type="radio" id="radio_rich_box" name="radio_rich_box" value="is_rich" / ><br />
Browseroutput
submit()
Createsa'submit'typebuttonfortheform. Theparametersare:
Example:
print form::submit('submit', 'Send');
ResultsinHTML
<input type="submit" id="submit" name="submit" value="Send" />
button()
Createsabuttonfortheform.Notethisisnotthesameasthebuttonassociatedwithinputtype 'submit'or'reset'. Theparametersare:
Example:
print form::button('button', 'Does not do Much');
ResultsinHTML
<button type="button" id="button" name="button">Does not do Much</button>
label()
Createsalabelforaformentryfield. Theparametersare:
Example:
print form::label('imageup', 'Image Uploads');
ResultsinHTML
<label for="imageup">Image Uploads</label>
attributes()
Returnsanattributestring,fromanarrayofHTMLattributesinkey/valueformat,sortedbyform attributesfirst. Theparametersare:
[array]HTMLattributesarray
Example:
print form::attributes(array('id' => 'input_name', 'class' => 'submission'));
Outputs
id="input_name" class="submission"
open_fieldset()
Createsafieldsetopeningtag Theparametersare:
[array]anarrayofHTMLattributes [string]astringtobeattachedtotheendoftheattributes
Example:
print form::open_fieldset(array('class' => 'important'));
ResultsinHTML
<fieldset class="important">
close_fieldset()
Generatesafieldsetclosingtag Example:
print form::close_fieldset();
ResultsinHTML
</fieldset>
legend()
Createsalegendfordescribingafieldset. Theparametersare:
Example:
print form::legend('More about you', array('id' => 'more_infos'));
ResultsinHTML
<legend id="more_infos">More about you</legend>
close()
Inordertoclosetheform,yousimplyneedto:
print form::close()
Oryoucansetparameter:
print form::close('</div>')
ResultinHTML:
</form></div>
HTMLHelper
TheHTMLhelperassistsincallingvariouselementssuchasstylesheet,javascript,imagelinksand anchorlinksintoposition.
Methods
specialchars()
'specialchars'issimilartoPHP'shtmlspecialchars()function.However,therearesomesmall differences:
Thetwoargumentsare:
Example:
$string = '<p>"I\'m hungry"—Cookie Monster said.</p>'; echo html::specialchars($string);
ItwillresultinthefollowingHTML:
<p>"I'm hungry"&mdash;Cookie Monster said.</p>
WhensettingthesecondparametertoFALSE,existingHTMLentitiesarepreserved.Lookclosely at—.
echo html::specialchars($string, FALSE);
query_string()
ThismethodisdeprecatedandwillnotbeavailableinKohana2.2.UsePHPfunction http_build_query()instead 'query_string'createsaHTMLquerystringfromanarray.Theoneargumentis:
[array]Thestringyouwanttoencode
Example:
echo html::query_string(array ( 'id' => 12, 'page' => 'home' ));
ItwillresultinHTMLas:
id=12&page=home
anchor()
'anchor'createsaHTMLanchor(<ahref=></a>),linkinganinternalpageorexternalsite automaticallyThefourargumentsare:
Example1:
echo html::anchor('home/news', 'Go to our news section!');
ItwillresultinHTMLas:
<a href="http://localhost/home/news">Go to our news section!</a>
Example2:
echo html::anchor('irc://irc.freenode.net/kohana', 'Join us on IRC!', 'style="font-size: 20px;"');
ItwillresultinHTMLas:
<a href="irc://irc.freenode.net/kohana" style="font-size: 20px;">Join us on IRC! </a>
file_anchor()
Similarto'anchor','file_anchor'createsaHTMLanchor(<ahref=></a>)linkingtononKohana resources.Therefore,itwillalwaysprefixthesite'sURLtothepathofyourfileThefourarguments
are:
Example1:
echo html::file_anchor('media/files/2007-12-magazine.pdf', 'Check out our latest magazine!');
ItwillresultinHTMLas:
<a href="http://localhost/media/files/2007-12-magazine.pdf">Check out our latest magazine!</a>
Example2:
echo html::file_anchor('pub/index.html', 'The Public Linux Archive', 'id="id432"', 'ftp');
ItwillresultinHTMLas:
<a href="ftp://localhost/pub/index.html" id="id432">The Public Linux Archive</a>
panchor()
Similarto'anchor',butacceptstheprotocolattributefirstinsteadoflastThefourargumentsare:
Example:
echo html::panchor('irc', '/kohana', 'Join us on our custom IRC!');
ItwillresultinHTMLas:
<a href="irc://localhost/kohana">Join us on our custom IRC!</a>
mailto()
'mailto'printsa<ahref=mailto:></a>tagbutescapesallcharactersoftheemailaddressinto HTML,hexorrawrandomlytohelppreventspamandemailharvesting.Thethreeargumentsare:
Example:
echo html::mailto('info@example.com');
ItwillresultinHTMLas:
<a href="mailto:info@exa ;mple.com">info@example&# x2e;com</a>
stylesheet()
'stylesheet'callsCSSfilesinternallyandwillsuffix.cssifitisnotalreadypresentThethree argumentsare:
Example:
echo html::stylesheet(array ( 'media/css/default', 'media/css/menu' ), array ( 'screen', 'print' ), FALSE);
ItwillresultinHTMLas:
<link rel="stylesheet" href="http://localhost/media/css/default.css" media="screen" /> <link rel="stylesheet" href="http://localhost/media/css/menu.css" media="print" />
link()
'link'callsfilessuchasfeedsinternally.Willrenderthe<link>tag.Linkingtostylesheetsalsouses the<link>tagbutthehtml::stylesheet()helpercanbeusedforthoseArguments
Example:
echo html::link(array ( 'welcome/home/rss', 'welcome/home/atom' ), 'alternate', array('application/rss+xml','application/atom+xml') , FALSE);
ItwillresultinHTMLas:
<link rel="alternate" type="application/rss+xml" href="http://localhost/welcome/ home/rss" /> <link rel="alternate" type="application/atom+xml" href="http://localhost/welcome/home/atom" />
script()
'script'callsJavaScriptfilesinternallyandwillsuffix.jsifnotpresentinyourfilecallTherearetwo argumentsare:
Example:
echo html::script(array ( 'media/js/login', 'media/js/iefixes.js' ), FALSE);
ItwillresultinHTMLas:
<script type="text/javascript" src="http://localhost/media/js/login.js"></script> <script type="text/javascript" src="http://localhost/media/js/iefixes.js"></script>
image()
'image'createsa'img'HTMLtag. Therearetwoargumentsare:
Example1:
echo html::image('media/images/thumbs/01.png');
ItwillresultinHTMLas:
<img src="http://localhost/media/images/thumbs/01.png" /> echo html::image(array('src' => 'media/images/thumbs/01.png', 'width' => '100', 'height' => 100, 'alt' => 'Thumbnail')); <img src="http://localhost/media/images/thumbs/01.png" width="100" height="100" alt="Thumbnail" />
Example2(withhtml::anchorandlightbox):
echo html::file_anchor('media/images/01.png', html::image('media/images/thumbs/01.png'), 'rel="lightbox"');
ItwillresultinHTMLas:
<a href="http://localhost/media/images/01.png" rel="lightbox"><img src="http://localhost/media/images/thumbs/01.png" /></a>
attributes()
'attributes'parsesattributesforaHTMLtagfromanarrayTherearetwoargumentsare:
[array]Anarrayofattributesyou'dliketoaddtoaHTMLtag
Example1:
echo html::attributes( array ( 'style' => 'font-size: 20px; border-bottom: 1px solid #000;', 'rel' => 'lightbox', 'class' => 'image' ) );
ItwillresultinHTMLas:
style="font-size: 20px; border-bottom: 1px solid #000;" rel="lightbox" class="image"
Example2(withhtml::anchor):
echo html::file_anchor('home/images/01.png', 'See my picture!', html::attributes( array ( 'style' => 'font-size: 20px; border-bottom: 4px solid #000;', 'rel' => 'lightbox', 'class' => 'image' ) ) );
ItwillresultinHTMLas:
<a href="http://localhost/home/images/01.png" style="font-size: 20px; borderbottom: 4px solid #000;" rel="lightbox" class="image">See my picture!</a>
breadcrumb()
Thefunctionreturnsanarrayoflinksforeachsegment.Arguments:
segmentstouseasbreadcrumbs,defaultstousingRouter::$segments
Example:
echo Kohana::debug(html::breadcrumb());
willproducethefollowingoutput:
Array ( [0] => <a href="http://localhost/ajax">Ajax</a> [1] => <a href="http://localhost/ajax/welcome">Welcome</a> [2] => <a href="http://localhost/welcome/text">Text</a> )
InflectorHelper
Providesmethodsforworkingwiththepluralizationandsingularizationofwordsaswellasother methodstoworkwithphrases.
Methods
uncountable()
inflector::uncountable($string)checkswhetherthegivenstringisanuncountable word.ReturnsTRUEorFALSE. Thismethodusesawordslistfromtheinflector.phpfile,locatedintothesystem/i18n/en_EN/folder (orthelanguagespecifiedintheconfigitem'locale.language')
inflector::uncountable('money'); //returns TRUE inflector::uncountable('book'); //returns FALSE
singular()
inflector::singular($string)willattempttosingularizethegivenstring.Returnsthe string.Ifastringisuncountableitwillreturnthestringwithoutmodification.Note:thisfunction worksforEnglishwordsonly.
inflector::singular('books'); //returns 'book'
plural()
inflector::plural($string)willattempttopluralizethegivenstring.Returnsthestring. Ifastringisuncountableitwillreturnthestringwithoutmodification.Note:thisfunctionworksfor Englishwordsonly.
inflector::plural('book'); //returns 'books'
camelize()
inflector::camelize($string)willattempttocamelizethegivenstring.Returnsthe string.
inflector::camelize('system_initialization'); //returns 'systemInitialization' inflector::camelize('system initialization'); //returns 'systemInitialization'
underscore()
inflector::underscore($string)makesaphraseunderscoredinsteadofspaced. Returnsthestring.
inflector::underscore('Underscores a phrase.'); //returns 'Underscores_a_phrase.'
humanize()
inflector::humanize($string)makesaphrasehumanreadableinsteadofdashedor underscored.Returnsthestring.
inflector::humanize('Remove_underscores_from_a_phrase.'); //returns 'Remove underscores from a phrase.' inflector::humanize('Remove-dashes-from-a-phrase.'); //returns 'Remove dashes from a phrase.'
NumberHelper
Providesmethodsforroundingintegernumbers.
Methods
round()
num::round()acceptstwoarguments.Anintegertoround,andanearestintegernumberto roundtoo,defaultsto5. Example
// Given an input of: $numbers = array(1,3,5,9,99,999); <p>Rounding numbers to nearest 5</p> <?php foreach ($numbers as $number): ?> <p>Round <?php echo $number ?> to <?php echo num::round($number, 5) ?> </p> <?php endforeach ?>
ThiswilloutputasHTML
<p>Rounding numbers to nearest 5</p> <p>Round 1 to 0 </p> <p>Round 3 to 5 </p> <p>Round 5 to 5 </p> <p>Round 9 to 10 </p> <p>Round 99 to 100 </p> <p>Round 999 to 1000 </p>
SecurityHelper
Thesecurityhelperassistinverifyingthesecurityofuseinput.
Methods
xss_clean()
'xss_clean'behavesthesameasxss_cleanintheInputlibrary.
[string]Stringtobecleansed
strip_image_tags()
'strip_image_tags()'stripstheimagetagsoutofastringandreturnsthestringtrimmedwithoutthe imagetags.
[string]Stringtobestripped
ItwillresultinHTMLas:
<b>Check this image:</b> http://www.example.com/example.jpg
encode_php_tags()
'encode_php_tags'replacesPHPtagsinastringwiththeircorrespondingHTMLentities.
[string]Stringtosantize
ItwillresultinHTMLas:
<?php echo "<b>Hello World!</b>" ?>
TextHelper
ProvidesmethodsforworkingwithText.
Methods
limit_words()
text::limit_words()acceptsmultipleparameters.Onlytheinputstringisrequired.The defaultendcharacteristheellipsis.
$long_description = 'The rain in Spain falls mainly in the plain'; $limit = 4; $end_char = '&nbsp;'; $short_description = text::limit_words($long_description, $limit, $end_char);
Generates:
The rain in Spain
limit_chars()
text::limit_chars()acceptsmultipleparameters.Onlytheinputstringisrequired.The defaultendcharacteristheellipsis.
$long_description = 'The rain in Spain falls mainly in the plain'; $limit = 4; $end_char = '&nbsp;'; $preserve_words = FALSE; $short_description = text::limit_chars($long_description, $limit, $end_char, $preserve_words);
Generates:
The r
alternate()
text::alternate()acceptsmultipleparameters.Thenumberofparametersdeterminesthe
alternation.Thisishandyifyouloopthroughsomethingandyouforexamplewanttoalternatethe colorofatablerow.
for($i=0:$i<5:$i++) { echo text::alternate('1','2','boom'); } //returns 12boom12
random()
text::random()acceptsmultipleoptionalparameters.Returnsarandomtextstringofspecified length. Possiblevaluesfor$typeare:
reduce_slashes()
text::reduce_slashes()reducesmultipleslashesinastringtosingleslashes.
<?php $str = "path/to//something"; echo reduce_slashes($str); // Outputs: path/to/something ?>
censor()
text::censor()acceptsmultipleoptionalparameters.Theinputstringandanarrayofmarker wordsisrequired.Returnsastringwiththemarkerwordscensoredbythespecifiedreplacement character.
$str = 'The income tax is a three letter word, but telemarketers are scum.'; $replacement = '*'; $badwords = array('tax', 'scum'); echo text::censor($str, $badwords, $replacement, $replace_partial_words = FALSE);
Generates:
The income *** is a three letter word, but telemarketers are ****.
bytes()
text::bytes($bytes,$force_unit,$format,$si)Returnsahumanreadablesize.
$bytesSupplythenumberofbites
widont()
text::widont()Returnsastringwithoutwidowwordsbyinsertinganonbreakingspace betweenthelasttwowords.Awidowwordisasinglewordattheendofaparagraphonanewline. It'sconsideredbadstyle.
$stringStringwithpotentialwidowwords
$paragraph='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras id dolor. Donec ...'; $paragraph=text::widont($paragraph);
URLHelper
ProvidesmethodsforworkingwithURL(s).
Methods
base()
url::base()returnsthebaseURLdefinedbythesite_protocolandsite_domainin config.php.
// site_domain = 'localhost/kohana/' // site_protocol = 'http' echo url::base();
Generates
http://localhost/kohana/
Generates
https://localhost/kohana/index.php
site()
url::site()returnsaURLbasedonthesite_protocol,site_domain,index_page, url_suffixdefinedinconfig.php.
// // // // site_domain = 'localhost/kohana/' site_protocol = 'http' index_page = 'index.php' url_suffix = '.html'
echo url::site();
Generates
http://localhost/kohana/index.php/.html
url::site()acceptstwooptionalparameters.YoucanpassURLsegmentsviathefirstone. Thesecondoneallowsyoutooverwritethedefaultsite_protocolfromconfig.php.
// // // // site_domain = 'localhost/kohana/' site_protocol = 'http' index_page = '' url_suffix = '.html'
Generates
https://localhost/kohana/admin/login.html
current()
url::current()returnsthecurrentURIstring.Thismethodacceptsoneoptionalparameter.If yousetittoTRUEthequerystringwillbeincludedinthereturnvalue.
// // // // site_domain = 'localhost/kohana/' site_protocol = 'http' index_page = 'index.php' url_suffix = '.html'
Returns
welcome/home
While
echo url::current(TRUE);
Returns
welcome/home?query=string
title()
url::title()returnsaproperlyformattedtitle,foruseinaURI.Thefirstparameter,theinput titlestring,ismandatory.Theoptionalsecondparameterisusedtosettheseparatorcharacter.By defaultthisisadash.Youcanonlychangethistoanunderscore.
$input_title = ' __Ecltic__ title\'s echo url::title($input_title, '_'); entered by crzed users- ?> ';
Generates:
eclectic_titles_entered_by_crazed_users
redirect()
url::redirect()generatesanHTTPServerHeader(302),whichwillredirectthebrowsertoa specifiedURL,bydefaultsite_domaindefinedinconfig.php. url::redirect()willalwayscallthephpexitfunctiontopreventfurtherscriptexecution.
url::redirect('http://www.whitehouse.gov');
WillredirectthebrowsertotheWhiteHousewebsite. Theoptionalsecondparametercanbeusedtosettheredirectmethod.Thedefaultis302.
// site_domain = 'localhost/kohana/' // site_protocol = 'http' url::redirect('aboutus', 301);
ValidHelper
Providesmethodsforvalidatinginputs.Itcurrentlyfeaturesvalidationforemailaddresses,ip's, url's,digits/numbersandtext.
Methods
email()
'email'checkwhetheranemailaddressisvalid.Itismorestrictthenthevalid::email_rfc()method.
[string]Emailaddresstovalidate
$email = 'bill@gates.com'; if(valid::email($email) == true){ echo "Valid email"; }else{ echo "Invalid email"; }
ItwillresultinHTMLas:
Valid email
email_rfc()
'email_rfc'validatesanemailaddressbasedontheRFCspecifications (http://www.w3.org/Protocols/rfc822/).Thisvalidationislessstrictthanthevalid::email()function.
[string]Emailaddresstovalidate
$email = 'bill@gates.com'; if(valid::email($email) == true){ echo "Valid email"; }else{ echo "Invalid email"; }
ItwillresultinHTMLas:
Valid email
url()
'url'doessomesimplevalidationonanURLtofindoutitifitcouldbeexisting.
[string]URLtobevalidated [string]protocoloftheURL(e.g.http,ftp)default=http
$url = 'http://www.kohanaphp.com'; if(valid::url($url) == true){ echo "Valid URL"; }else{ echo "Invalid URL"; }
ItwillresultinHTMLas:
Valid URL $url = 'ftp://ftp.kohanaphp.com'; if(valid::url($url,"ftp") == true){ echo "Valid URL"; }else{
ItwillresultinHTMLas:
Valid URL
ip()
'ip'validatesanIPaddresstomakesureitcouldexist,butdoesnotguaranteeitactuallydoes.
[string]IPaddresstobevalidated
$ip="123.456.678.912"; if(valid::ip($ip) == true){ echo "Valid IP"; }else{ echo "Invalid IP"; }
ItwillresultinHTMLas:
Invalid IP $ip="65.181.130.41"; if(valid::ip($ip) == true){ echo "Valid IP"; }else{ echo "Invalid IP"; }
ItwillresultinHTMLas:
Valid IP
alpha()
'alpha'checkswhetherastringconsistsofalphabeticalcharactersonly
[string]Stringtobevalidated [boolean]IftrueUTF8modewillbeuseddefault=FALSE
$string="KohanaPHP is cool"; if(valid::alpha($string) == true){ echo "Valid string"; }else{ echo "Invalid string"; }
ItwillresultinHTMLas:
Invalid string $string="KohanaPHPiscool"; if(valid::alpha($string) == true){ echo "Valid string"; }else{ echo "Invalid string"; }
ItwillresultinHTMLas:
Valid string
alpha_numeric()
'alpha_numeric'checkswhetherastringconsistsofalphabeticalcharactersandnumbersonly
[string]Stringtobevalidated [boolean]IftrueUTF8modewillbeuseddefault=FALSE
$string="KohanaPHP Version 2 is cool"; if(valid::alpha_numeric($string) == true){ echo "Valid string"; }else{ echo "Invalid string"; }
ItwillresultinHTMLas:
Invalid string $string="KohanaPHPVersion2iscool"; if(valid::alpha_numeric($string) == true){ echo "Valid string"; }else{ echo "Invalid string"; }
ItwillresultinHTMLas:
Valid string
alpha_dash()
'alpha_dash'checkswhetherastringconsistsofalphabeticalcharacters,numbers,underscoresand dashesonly
[string]Stringtobevalidated [boolean]IftrueUTF8modewillbeuseddefault=FALSE
$string="KohanaPHP Version 2 is cool"; if(valid::alpha_dash($string) == true){ echo "Valid string"; }else{ echo "Invalid string"; }
ItwillresultinHTMLas:
Invalid string $string="KohanaPHP_Version-2-is_cool"; if(valid::alpha_dash($string) == true){ echo "Valid string"; }else{ echo "Invalid string"; }
ItwillresultinHTMLas:
Valid string
digit()
'digit'checkswhetherastringconsistsofdigitsonly(nodotsordashes)
[string]Stringtobevalidated [boolean]IftrueUTF8modewillbeuseddefault=FALSE
ItwillresultinHTMLas:
Invalid $digits = "2342432"; if(valid::digit($digits) == true){ echo "Valid"; }else{ echo "Invalid"; }
ItwillresultinHTMLas:
Valid
numeric()
'numeric'checkswhetherastringisavalidnumber(negativeanddecimalnumbersallowed)
$number = "-23424.32"; if(valid::numeric($number) == true){ echo "Valid"; }else{ echo "Invalid"; }
ItwillresultinHTMLas:
Valid
standard_text()