Evik James
Evik James

Reputation: 10483

Which is the right scope to use?

I am using ColdFusion 9.0.1

I am running a page that will include other pages. The main purpose of this page is to determine which page to include. The pages that will be included will make use of the variable that I use in the page, which will be the MovieID (in this case).

My question is which is the best scope to use on this page? Would it be VARIABLES?

<cfscript>
Lookup = CGI.QUERY_STRING;
Query = CFC.doLookup(Lookup);
if (Query.RecordCount == 0) {
    include "Content/Home.cfm";
} else {
    // MOVIE PAGE
MovieID = Query.MovieID; // WHAT SCOPE SHOULD I USE HERE? FOR MOVIEID?
include "Content/Movie.cfm";
}
</cfscript>

Upvotes: 1

Views: 107

Answers (3)

Mike Causer
Mike Causer

Reputation: 8314

Yes: Variables

Maybe: Application, Cookie, Request, Server, Session

No: Arguments, Attributes, Caller, CGI, Client, Flash, Form, Local, This ThisTag, Thread, thread local, URL

For info about each scope, check the CF9 documentation: scope types.

Sounds like you're implementing a Front Controller pattern.

Implement an Application.cfc, with an onRequest() that runs your code snippet. That way, it would intercept all incoming requests and include the appropriate cfm. Skipping the need for a handler index.cfm which simply includes the other cfm templates.

A further optimisation. Have your doLookup() method return a Struct containing just the recordCount + movieId as it appears that is all you are using. Returning a whole query is slower than just a struct of two numbers.

CF9 documentation: Application.cfc.

Upvotes: 3

Steve Bryant
Steve Bryant

Reputation: 1046

Although either Variables scope or Request scope will be available to an included page, using Request scope could be helpful inasmuch as it is a scope that is intended to be available to any file in the request, whereas Variables scope is generally perceived to be specific to a given page.

In fact, Request scope was originally introduced for Allaire Spectra for the purpose of sharing variables across custom tags.

So, while both will do what you want, I would say that Request scope may have a small advantage of clarifying intent just a bit more.

Upvotes: 2

Jake Feasel
Jake Feasel

Reputation: 16955

Variables (which is what you have now) certainly works. Another reasonable option would be Request, but I would lean toward variables over request.

Upvotes: 3

Related Questions