CALLER Scope


CALLER Scope

The relationship between a regular template file and a Custom Tag can often be one-sided, meaning that the template passes information to the Custom Tag but not vice versa. There are instances, however, when the Custom Tag should pass data back to the calling template.

A login script for security can be wrapped into a Custom Tag. This script will take the user name and password passed into it, along with attributes that declare which data source and table to authenticate against, and pass back a flag that declares whether the user has logged in successfully.

Most often in a scenario like this, the name of the flag being returned to the calling page is determined by the person who created the login Custom Tag. If you're working in a team environment, this is not always ideal because your team has most likely created coding standards for the naming of variables. Therefore, it would be better if you could tell the Custom Tag what you would like to name the variable being returned, as in the following Custom Tag call:

 <cf_loginscript username="#FORM.UserName#"  psswd="#FORM.PSSWD#"  datasource="dsn"  tablename="Users"  loginflag="LoginFlag"> 

The preceding code declares that the username and password are being passed from a form submission and that the loginflag returned should be named LoginFlag.

To create a local variable from within a Custom Tag, you simply type the following code, just as you would for any local variable:

 <cfset LoginFlag="1"> 

Local variables are introduced in Chapter 2, "Working with Variables and Expressions."


To create this variable in the calling page, you must prefix it with CALLER:

 <cfset caller.LoginFlag="1"> 

CALLER tells ColdFusion to let this variable escape the protection of the Custom Tag and make it available to the calling page. This code is perfectly legal, but it is also dangerous: Hard-coding variable names is never a good idea.

To dynamically name and create the variable, you could use this:

 <cfset "Caller.#ATTRIBUTES.LoginFlag#"="1"> 

Because we declared that ATTRIBUTES.LoginFlag will have a value of LoginFlag, the variable is ultimately named CALLER.LoginFlag, and because of the Caller. prefix, it will be exposed to the calling page.

TIP

As a rule, Custom Tags should never arbitrarily create variables in the CALLER scope. Always allow caller code to specify the name of the variable to be created so that Custom Tag code does not inadvertently overwrite other variables.




Macromedia ColdFusion MX 7 Certified Developer Study Guide
Macromedia ColdFusion MX 7 Certified Developer Study Guide
ISBN: 0321330110
EAN: 2147483647
Year: 2004
Pages: 389
Authors: Ben Forta

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net