Skip to content

Instantly share code, notes, and snippets.

@QasimTalkin
Last active July 5, 2022 13:33
Show Gist options
  • Select an option

  • Save QasimTalkin/f0013090b33fc9b7f3e86a62f4953797 to your computer and use it in GitHub Desktop.

Select an option

Save QasimTalkin/f0013090b33fc9b7f3e86a62f4953797 to your computer and use it in GitHub Desktop.
CFML in 30 mins : ColdFusion Quick Start

0.0.1 CFML in 30 mins

0.0.2. Two syntax

  • tag based <cfoutput> #somevar# </cfoutput>
  • script based <cfscript> writeoutput("sada") </cfscript>

0.0.3. Commentsstart

Server side or Cf comments

<!--- cf comments "high level logic --->

Client comment

<!-- Client comments can be used for div tags -->

CF script comments //single line /* multiline */

0.0.4. cfdump and writedump

  • green array
  • blue structure <cfdump var = #somevalue# abort label="doing stuff">
  • attribute -> abort! ( good for debug)
  • attribute -> label ( giving header for info)
  • writedump cfscript version of cfdump!

0.1. Variables and DataType

set var <cfset var = 'Qasim'> output var #var#

  • only valid symbol to use before the name is $var
  • not case sensitive. can use var and then display using #VAR# (JS IS CASE SENSITIVE)
  • should not start with a number
  • loosely typed does not require to declare data type.

0.1.1. List

<cfset varlist = "1,3,5">

<cfscript>
    // change list delimiter 
    newlist = listChangeDelims(varlist, $)
    // lsit length 
    Listlen(newlist, $)
    counting empty list items 
    list = "dasda,asd,asd,asd,ada,da,,,,sadadas,d,d,asd"
    LenList(lsit, ",", true)
    ListGetAt(list, 1)
    //if wanting to count empty items 
    ListGetAt(list, 1, ",", true)
    // finding item in the list
    // returns 1 upon finding an item
    fountItem = Listfind(list, "somevalue ") //case sensitive and match exact
    foundItem = ListContains (list, "somev") //also case sensitive 
    // Remove case sesiuteve by atting NoCase
    listFindNoCase
    and 
    listContainsNoCase
</cfscript>

0.1.2. Array

  • Array start with 1 in cold fusion.
  • modern way to apped into an array (araryban.append()) Member Function
  • loosely typed (does not store same type of data )

0.1.2.1. creating arrays

         myOneDemArray = arrayNew(1); 
         myOneDemArray = ["1", "2"] 
         myOneDemArray[1] = "Qasim"; 
         arrayAppend(myOneDemArray, "Qaszim");
        // can use member function
        myOneDemArray.append("red");
        // we can store diffrent types of data in the array sice its loosely typed 
        myOneDemArray.append(23);
        myOneDemArray.append(dayOfWeekAsString(3));
       //since array are complec object we use cfdump
        writeDump(myOneDemArray);

0.1.3. Finding array

returning the first/last item in array arrayName.fisrt(); arrayName.flast()); find array arrayname.find("qasim"); or Arrayfind(arrayname, "Qasim") -> return theindex findNOcase (NoCase) -> still needs complete record name AarrayContains (NoCase) -> return true or false based if it finds the value unlike list that returns the index

0.2. array function

Append (arrayName, true/false (merge or not)) -> arrayname.appne(next array) add an arary to the index

several other funcions avaialabe, prpend-> adds in the begning inset -> at a specic location ("3, "Qasoim) delete, deleteat -> delteat(2)

0.2.1. Structure

var = StructureNew() or var = {key:"value"

  • key names are not case sensitive
  • basic copy of struct get copies but if struct excite within a struc.t "inm.ternal struct could be large it does not copy it but points to using it as refrence
  • if you copy it other wise you can work aroud it using duplicate()

0.2.2. The Null construct

  • No value is undefined -> null has a value null
  • null support enable.
var = null;

0.2.3. Scope in CF

//get all vars with 

#variables#
and 
#variable.count()#

  • CGI Scope
    • read only scopes
    • CGI Environment variables contain data about the transaction between the browser and the server, such as the IP Address, browser type, and authenticated username.
  • Application.cfc
    • capital Application
    • loads before everything.
    • loads it from the folder, if not found looks up entire server directory
    • executes it before cfm and stops searching for other cfc files
    • first one first execute.

Each request on web is a unique transaction, limitation to pass data can be overcome by persistent scope in cfc. picture 3

  • Session scope
    • user specific scope.
    • CF checks for cftoken in cookies and uses it match the existing session
#cookie#
  • ServerScoepe #server# variable scope

all includes and current cfm adds to variable scope. last var assigned value among duplicates.

0.3. Include

  • constants use CAPS to make the code more readable use const to CF include the
  • Include math or function library -works like variable order for functions to in case of same function names.
  • avoid include within include

Application CFC

- application.cfc loads from the root of thr project. 
- common setting live in this scope

this.blockedExtForFileupload = "cfm, cfc"

Application Strart

-> Http request event listener and handlers

START -> all app global vars onapplicationStart(){ application. }

ON Session -> user sesssion vars onSessionStart(){

}

  • both run only time

APP.cfc., -> onRequestStart -> starts on request request -> onError()

Basic database operations

DSN

* Data source name. 

cfQuery.

<cfquery name="news">
    SELECT id,title,story
    FROM news
    WHERE id = <cfqueryparam value="#url.id#" cfsqltype="cf_sql_integer">
// cfscript 
myQuery = queryExecute(
 "SELECT myCol1, myCol2 FROM myTable 
  WHERE myCol1 = :myid 
  ORDER BY myCol1 ASC ", 
  {myid: 5}, 
  {datasource = "myDSN"} 
);

queryObj = new Query(
 name="qryDemo",
 // datasource not reqwuried unless connecting to a diffe4rnt data source . 
 datasource="mydatasourcename",
 sql = "SELECT col1, col2
 FROM myTable
 WHERE id=:id"
); 
queryObj.addParam(name="id",value=arguments.id, cfsqltype="cf_sql_integer");
resultset=queryObj.execute().getResult();


writeDump(myQuery);
</cfquery>

output Query.

first user
writedump(queryObj.firrstname) 
//or loop over query 
 for each in queryObj {
    writedump(each.firrstname); 
 }

query option

  • maxrows = 4
  • startrow = 3
  • group="row name"

Dynamic Queries params

  • sql injectin
  • use pram and type of attribute <cfqueryparam value="#url.id#" cfsqltype="cf_sql_integer">
  • recordcount
  • columnlist
  • currentrow

QueryExecute (1,2,3) 3 params -> sql, params, options options -> {results= , cashedwthin =}

cashing queryiee.

cashedwithin = createTimespan (0,0,5,0)//5 mins Query

sql = "SELECT njiActivityID FROM tblPdpActivities where person_id = :Person_id";
params = {Person_id={value=currentuser, cfsqltype="cf_sql_integer"}};
userActivities = queryExecute(sql, params, {datasource = "datdabaseif", cachedwithin=createTimespan(0, 0, 3, 0)}); 

Queries of Queirus.

dbtype = query //get data frm another query

from -> give queryname.

3 Querylist

Valuelsut (columnname, 'delim ;')

other tags and Fucntions.

  • directory ->
myList = directoryList(expandPath("./"), false, "query"); 

<cfdirectory action="list" directory="#expandPath("./")#" recurse="false" name="myList">

attribute ->

  • recures = trur ->> adds sub direcoryt
  • sort = direcorty acs, name desc and so on.
  • cdldap -> ldap server.

Components

main

  • end in cfc file extension.
  • written in cfscript
    • with component { }
  • this scope present
    • object.varibalename will give the value of the var in this scope.
  • variable scope.
    • variable is not accessible
  • instantiate component using CreateObject to use it

creating methods(function)

  • method (a function inside a component)
  • pass and return argument and data
  • return numeric -> public number else -> public any or public void
  • Public (can be used inside cfc and its instances )
  • Private (only within cfc)
  • init contractor
    • use new keyword to create instance of a component similar to creatObject
      • myobj= new filepath.student() for student.cfc in filepath folder

contractor method

  • used to initialize, can have arguments and help to store data
  • init is the contractor method.
  • returns this -> ref to object instance being created.
  • other langs insted of init they use class name.

public and Private

  • Public (can be used inside cfc and its instances )
  • Private (only within cfc)
  • in oop make var and fun conly when needed
  • avoid global vars
  • app is eay to make and grow other OO protected -> similar to cf private.

accessor scope.

  • getter and setter (accessors and mutators. )
  • setter return type void.
  • better way to work makes application smarter. using fucntion funcName (number arg1, string arg2 ...)

cf-property and implicit accessors. (auto default behaviour (set, get))

  • property type and name implicitly declares accessors and mutator property name="qasmi" type="String"
  • along with property have component accessor = "true" { property name='arg1' type='number' public any fucntion init (){set..(), set...arg2(createUUID())}}
    • added setters and getters automatically.
  • if validation required it could also be added manually. for error validation.

prmiray unique keys

  • when declaring unique property type = 'uuid'
  • settter must be set to false to get unique id
component accessor = "true" { 
    property name='arg1' type='number';
    property name='arg2' type='uuid' setter='false';
    public any fucntion init (){
   set...arg1('qasim');
   varible.arg2 = creatuuid();
    }}

inheritance 'is a'

  • components sharing data 'some unique data and some same data'
  • varibales sharing
  • method sharing
  • teacher, principal, supervisor all emaployes of a school
  • they share some props and have similar methods
  • build a relation to these props isnted of seprate method

extends attribute

  • Emaploye -> name, age, showinfo();
  • teacher extends emaployee component acessor= 'true' extends = 'Employee'

Super keyword

  • isnted of calling setfuc we can use super constructor
    • super.init(argument.name, argument.age);

human -> employee -> teacher

Abstract

  • abstract component

best practice inheritance

- ignore everyting in one Cf compoent 
- seprate CFC
- try to describe object relation as a conversaion sentence. 

composition 'has a'

  • one object ahs anothe object in it
  • setting property name='hasa' type = 'foldername.CFCObject'
  • passing obj as argument
  • calling has a object hasa.fucntionCall()

interface

- Dog  -> var name, age, coclor 
- fucntion -> sound, eat, run
- store selles other aniamls with similar proeprty. 
- `componenet impliments = 'Iinterfacefile'`
- `componenet impliments = 'Iinterfacefile, Isecondinterface'`

CURD opreations

  • CFCObject
  • select Select sample
  • Insert Insert sample
  • update update
  • Delete Delete Query

searching in Query

search sample

Model layer

  • CURD
  • cfc resposible for multiple fucntionality
  • one cfc dealing with multiple tables?

Caching

Caching compoenets

  • create CFC -> init -> call func
  • ifespan on object end with end of file.
  • 10 times calls -> 10 runs on creating object.
  • Treasiant request crerates object again and again when object created.
  • Applicaiton.cfc -> onApplicationStart()
  • store the obj in application socep application.objMovie = new modal.Movie()
  • singleton singel object at singel space.
  • object gets saved

Session Caching

  • cfc can be stored in Session Scope.
  • session.varname = obj specfic to user

cachin variable

  • helps in performace 'heve data only called once'
  • cacheput('key varibale name', 'varaibel to cache')
  • cacheget('key varibale name')

ORM (object relation mapping -> get dta from and save data to DB)

  • little or no sql
  • maps data to object
  • Hibernate fraemwork baked into Coldfuison
  • regardsless of DB same Code
  • this.ormenalbled=true
  • Convert to ORM cfc componenet persistent=true table='tblusers{ f}'
  • acessor aut set
  • on app start set up all orm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment