cold fusion/cfml: a primer by hansjoerg posch
DESCRIPTION
A CF tutorial covering the basics of Adobe ColdFusion and CFML. Handling DB stuff, exceptions, flow control and much moreTRANSCRIPT
© 2008 by Hansjörg Posch Founder & CTO of tunesBag.com http://CFstuff.blogspot.com http://www.linkedin.com/in/hansjoergposch
Logo © by Adobe
What is CF? The language Anatomy of an application Database access Flow control Reusing code Error handling
CF: A primer by Hansjoerg Posch
ColdFusion is an Application Server CFML is compiled to Java Bytecode
Client (Browser / Webservice)
Webserver (Apache/IIS)
ColdFusion (running on App Server)
DB (JDBC) Mail Files Webservices
CF: A primer by Hansjoerg Posch
Multiple Platforms Windows, Linux, Mac & Solaris
App‐Server / JVM JRUN (bundled), Sun One, Jboss or Weblogic
WebServer (Apache/IIS) Databases Any JDBC driver, available for mySQL, MS‐SQL, PostgreSQL, Oracle etc
CF: A primer by Hansjoerg Posch
BlueDragon (www.newatlanta.com) including CFML for .Net
OpenBlueDragon (www.openbluedragon.org) BlueDragon as open source
Railo (www.railo.ch) lightweight CFML from CH
Smith project CFML opensource platform
Standard = Adobe ColdFusion (adobe.com) CF: A primer by Hansjoerg Posch
• Two ways of writing code • Tag based (all features supported)
<cfset variables.firstname = "Peter" /> <cfoutput>#variables.firstname#</cfoutput>
• Script based (limited support for various stuff) <cfscript> Var firstname = "Peter"; WriteOutput(firstname); </cfscript>
CF: A primer by Hansjoerg Posch
<!--- query the database ---> <cfquery name=„q_select“ datasource=„db01“> SELECT id,firstname,surname,birthday FROM contacts WHERE id > <cfqueryparam cfsqltype="cf_sql_integer" value="#url.id#"> ; </cfquery>
<!--- output ---> <cfoutput query=„#q_select#“>
<a href=„details.cfm?id=#q_select.id#“>#q_select_surname#</a>
(Birthday: #Year( q_select.birthday )#)
<cfif q_select.surname IS „“> Last name is empty! Fix it! </cfif> <br />
</cfoutput> CF: A primer by Hansjoerg Posch
What you need WebServer (Apache recommended) Database Server (mysql recommended) Adobe ColdFusion Trial or Developer Edition (FREE!) – www.adobe.com
Eclipse – www.eclipse.org CFEclipse – www.cfeclipse.org
CF: A primer by Hansjoerg Posch
• Administration • Application • Variables / Scopes • Database access • Output • Operators • Flow Control • Components • Session handling • Error handling
CF: A primer by Hansjoerg Posch
Set up database connections using JDBC Enable/Disable debugging mode Request timeouts Template caching Schedule tasks Connection to mail server JVM arguments Simultaneous Template requests Demo
CF: A primer by Hansjoerg Posch
Created by adding an Application.cfm or .cfc in the root directory of your app
Use CFAPPLICATION to set various properties including session timeout etc
This base File is executed on every request! Set DSN, paths, check login etc
To do some cleanup/logging: Use the file onRequestEnd.cfm
CF: A primer by Hansjoerg Posch
CF is weakly typed (components = strict) Common ways to create variables
<cfset firstname = "Peter" /> Result of a tag, e.g. <CFHTTP ... Result="webpage" />
Naming conventions Letters, digits, underscores and $ Cannot begin with a digit Case‐insensitive
CF: A primer by Hansjoerg Posch
Variables can live in various scopes, therefore always use the full notation, e.g. <cfset variables.firstname = "Peter" /> <cfoutput>#application.copyright#/</cfoutput>
If no notation is used, CF will search trough the scopes (performance!) in the following order: Arguments, Variables, CGI, URL, Form, Cookie, Client
CF: A primer by Hansjoerg Posch
Name Scope Access
Local VARIABLES Current page only
URL URL All pages
Formular FORM All pages
CGI CGI All pages
Client CLIENT All pages
Arguments ARGUMENTS Within CFFUNCTION
Session SESSION All pages
Application APPLICATION All pages
Server SERVER All pages
Request REQUEST All pages CF: A primer by Hansjoerg Posch
CFPARAM Make sure a variable exists, e.g. <cfparam name="url.firstname" type="string" default="Peter" />
StructKeyExists = does a certain variable exist? <cfif StructKeyExists( session, "userid")> ...
CFDUMP Output all data of the given argument/scope <CFDUMP var="#application#" />
CF: A primer by Hansjoerg Posch
Locking using CFLOCK is needed to avoid race conditions
Race condition = Two threads access same variable in R/W at the very same time
Locking is ONLY needed in case ... You‘re accessing the variable in R/W mode For shared scopes including SESSION, APPLICATION, SERVER and certain tags
Demo (Application.cfm)
CF: A primer by Hansjoerg Posch
Database is queried using CFQUERY – tag <cfquery name="q_select" datasource="xy"> ...
Datasource must be created in the CF Admin Use CFQUERYPARAM to avoid SQL injection
SELECT a FROM b WHERE c = <cfqueryparam cfsqltype="cf_sql_integer" value="#url.id#">
Inspect the result: CFDUMP = Show whole query query.columnlist = list of returned columns query.recordcount = recordcount
CF: A primer by Hansjoerg Posch
Query of queries: Use cfquery to work with existing query objects using dbtype=„query“
Example <cfquery name="q_select_firstnames" dbtype="query"> SELECT firstname FROM q_select WHERE id > 100 </cfquery> Creates a new query leaving the original one untouched
Demo (query.cfm)
CF: A primer by Hansjoerg Posch
CFOUTPUT is THE tag to output data <cfoutput>#url.firstname#</cfoutput> <cfoutput query="#qry#">#qry.firstname#</cfoutput> <cfoutput>Today is #Now()#</cfoutput>
In case of a query, CF will loop over all given rows (use startrow/maxrow to paginate)
One CFOUTPUT can be used for a block or even the whole page
CF: A primer by Hansjoerg Posch
Within a CF‐tag, no # are needed except the expression is in quotes <cfset session.name = "Dear Mr #surname#" /> Better:<cfset session.name = "Dear Mr " & surname />
Nested functions: Only use # for the outermost function, e.g. <cfoutput>The year #Year( Now() )# is simply great</cfoutput>
CF: A primer by Hansjoerg Posch
Type Operator
Name Example
String & Concat <cfset variables.name = url.firstname & „ „ & form.surname />
Arithmetic + Addition <cfset total = a_sum + 200 />
‐ Subtraction <cfset b = 500 – a />
* Multiplication <cfset x = b * t />
/ Division <cfset x = v / 3 />
MOD Modulus <cfset x = b MOD 3 />
Decision operators will follow later CF: A primer by Hansjoerg Posch
HTML comment = <!– comment ‐‐> CF comment = <!‐‐‐ comment ‐‐‐> (three dashes) Stripped out of the final page content!
Comments in scripts: <cfscript> // set the firstname var firstname = "Peter"; </cfscript>
CF: A primer by Hansjoerg Posch
Standard HTML form tag with various inputs CFFORM / CFINPUT can be used for client‐side validation <cfinput required="true" validate="email" ... NOT recommended due to customization troubles
Action = GET will result in URL parameters Action = POST will result in FORM parameters
Demo (form.cfm) CF: A primer by Hansjoerg Posch
IF / THEN / ELSE (optional) <cfif condition> ... <cfelse> ... </cfif> Condition = must return TRUE / false or 0/1 Demo
IF / THEN / IF ELSE / ELSE CFSWITCH – switch blocks
Various CFCASEs plus a CFDEFAULTCASE CFBREAK – exit a loop CFEXIT (method="exittemplate“) exit a template
CF: A primer by Hansjoerg Posch
Type Operator Description
Decision IS / EQ TRUE if equal (case‐insensitive)
IS NOT TRUE if not equal
GT Greather than (left than right)
LT Less than (left than right)
CONTAINS TRUE if left value contains the right value
DOES NOT CONTAIN
Boolean NOT Reverse value
AND
OR
Use brackets to structure decisions, e.g. <cfif ((a OR b) AND (c OR d)) OR g> .... </cfif>
CF: A primer by Hansjoerg Posch
Index loops = from a to b by step c Conditional loop = continue as long as long as condition = true
Loop over list = loop over items of a list (default delimiter = comma)
Loop over query (cfloop query=""xy) ... Will NOT output the data automatically.
Further uses: collections, structures etc Exit a loop: CFBREAK
CF: A primer by Hansjoerg Posch
CF is NOT zero‐based, so the 1st item has the index 1 NOT zero
Lists = Strings delimited by a certain char Array = One or multi‐dimensional Arrays Structure = key/value pairs Demo (list.cfm)
CF: A primer by Hansjoerg Posch
ListFind(NoCase) ListContains(NoCase) ListLen ListFirst / ListLast ListGetAt ListDeleteAt ListAppend / ListPrepend / ListInsertAt TIPP: ValueList( q_select.firstname )
CF: A primer by Hansjoerg Posch
Created using ArrayNew(Dimension) <cfset a_names = ArrayNew( 1 ) /> <cfset a_names[ 1 ] = "Peter" />
Important functions ArrayLen ArrayToList ArrayAppend / ArrayPrepend / ArrayInsertAt ArrayClear ArraySort
CF: A primer by Hansjoerg Posch
Key/Value paris created using StructNew() <cfset a_names = StructNew() /> <cfset a_names.Doe = "John" />
A structure can hold all kind of data / objects including queries, arrays, other structures etc
FORM, URL, CGI, ... Are all structs! Important functions
StructCount / StructKeyExists / StructKeyList StructClear
CF: A primer by Hansjoerg Posch
CFINCLUDE = include a .cfm file template = relatively to the current template <cfinclude template="inc_header.cfm" />
UDF = User defined functions CFFUNCTION ▪ Can receive strictly typed arguments
Functions in CFSCRIPT ▪ Perfect for small helper functions
CF: A primer by Hansjoerg Posch
Limited support for various stuff (no usage of tag‐based features)
Declare local variables with the keyword VAR at the top
Can use arguments and return a value or use WriteOutput to return data
Can call other functions or even components (using CreateObject() )
Demo (reuse.cfm) CF: A primer by Hansjoerg Posch
All the business logic should be put into CFFUNCTIONS to enable strict data type handling Name = Name of function Returntype = various types including void (no return)
CFFUNCTION can output data but you should only return data if possible (output=„false“)
CF: A primer by Hansjoerg Posch
Declare local variables used in the function on top using the keyword VAR to avoid locking etc
Add the expected CFARGUMENTs – including types, default values and required attribute
Add Hints and descriptions for easier auto‐Doc Extending of other components is possible Multiple CFFUNCTIONS can be combined to a CFCOMPONENT
CF: A primer by Hansjoerg Posch
Similar to classes in OO – languages Used to abstract business logic / processing CFFUNCTION access control
Private = Only same page / component Public = All pages Remote = Accessible via WebService Package = Same directory
Demo (cmp.cfc)
CF: A primer by Hansjoerg Posch
Invoke a component CFINVOKE ... Tag based createObject( ‚component ‚) ... Script based
Inspect all functions using CFDUMP! Demo (component.cfm)
CF: A primer by Hansjoerg Posch
CFMAIL = used for sending emails over SMTP, supports multipart/alternative
CFPOP = fetch mails from server
CF: A primer by Hansjoerg Posch
CF uses the Apache DOM parser for creating & reading XML data
CFXML / XMLNew allow you to create a new XML document Demo
XMLParse to build DOM from string XMLSearch/XPATH to search for data All XML Nodes are structures and arrays! Demo (xml.cfm)
CF: A primer by Hansjoerg Posch
Advanced XML features XMLTransform: Transform a XML document using a XSL stylesheet / parser
XMLSearch: XPATH supports all default expressions, e.g. "//items/item/surname/text()"
XmlGetNodeType: Get the node type XmlValidate: Validate against a DTD schema
CF: A primer by Hansjoerg Posch
CFFILE = Read/Write a file <cffile action="write" file="/tmp/test.txt" output="#a_str_text#">
CFHTTP = Read/Write to a webserver <c|ttp charset="utf‐8" method="get" url="http://www.tunesBag.com" result="c|ttp"></c|ttp>
CF: A primer by Hansjoerg Posch
Compiler errors during compiling Syntax errors (e.g. "<cfof>" instead of "<cfif>"), missing required attribute etc.
Should all be handled & fixed during development Exceptions on runtime
Thrown on runtime, can be catched using <cftry> ... <cfcatch type="any"> ... </cfcatch></cftry>
Site‐wide error handling possible (see CFAdmin) Demo
CF: A primer by Hansjoerg Posch
Caching should be used to gain performance but only when necessary
Query result caching (using CACHEDWITHIN) Page content caching (using CFCACHE) Cache data in application / session scope
Don‘t forget the locking Demo
CF: A primer by Hansjoerg Posch
/Application.cfc /components/cmp_contacts.cfc /components/queries/q_select_contact.cfm /contacts/default.cfm /contacts/dsp_contact.cfm /contacts/actions/act_delete_contact.cfm /common/inc_scripts.cfm
CF: A primer by Hansjoerg Posch
A_str_name = local variable <cfset variables.a_str_name = ‚Peter‘ /> <cfset variables.a_struct_demo = { surname = "Doe" }/> <cfloop index="#a_int_ii#" ...> ... </cfloop>
Cmp_contacts = Component <cfset cmp_contacts = createObject( "component", "/components/cmp_contacts" />
CF: A primer by Hansjoerg Posch
Use CFFUNCTIONS for business logic Prefer Struct to Array, Array to List Use the full scope when accessing variables CFSWITCH over CFIF Keep CFFUNCTIONS as independent as possible, pass values to calls instead of reading them directly
Introduce a good naming schema
CF: A primer by Hansjoerg Posch
Reports – CFREPORT JSON / AJAX Support CFHTTP / CFFILE operations Webservices Custom Tags (Java / C++) RSS Feeds, Captchas Jabber, SMS, Gateways Image manipulation
CF: A primer by Hansjoerg Posch
MVC: Mach‐II (www.mach‐ii.com) ColdSpring: Glue your components together (http://www.coldspringframework.org/)
Transfer / Reactor: ORM for less SQL (www.transfer‐orm.com)
jQuery: Powerful client‐side JS – library (www.jquery.com)
Adobe LiveDocs (livedocs.adobe.com) More Tutorials: www.google.com/search?q=coldfusion+tutorials
CF: A primer by Hansjoerg Posch
Enjoy coding in CF! Check out www.tunesBag.com, a cool website done completly in CF!
CF: A primer by Hansjoerg Posch