structGet()

So, I’m going to try something new - random postings about CFMX tags/functions that you may not be too familiar with. If you like this, please post a comment and I’ll continue.

structGet() is an interesting function. Basically, it allows you to create a N-deep structure simply by defining a path. So, for example, structGet(“grandparent.parent.child.grandchild”) will (may, see below) create four structures. It will first create a structure called grandparent. It will then create a structure called parent and set it inside of grandparent. It will continue doing this until it reaches the end, the grandchild structure.

What’s nice about structGet is that it’s smart enough to see if a structure already exists. Using the same code as above, if grandparent.parent already existed, it would only create two structures, child and grandchild.

When you run structGet, it returns a pointer/reference to the structure created. This is useful if the path is dynamic:

path = “foo.goo.zoo.moo”;
ptr = structGet(path);

The variable, ptr, is actually a reference to foo.goo.zoo.moo. Here is an example of structGet in action:

<cfscript>
ptr = structGet(“server.cache.nav.menu”);
dump(var=ptr);
ptr.value = 9;
dump(var=server.cache);
</cfscript>

In case you are wondering, no, you can’t call <cfdump> from within cfscript - unless you take two seconds and write a cffunction based version of dump.

When you run this code, structGet will obviously not need to create the server structure since it already exists. However, “cache.nav.menu” will be created as three linked structures. If you then modify ptr, you will see it reflected when you dump server.cache.

Another interesting aspect of structGet is that it will create arrays as well. Consider the following line of code:

ptr2 = structGet(“server.pageRanks[3].data”);

This will create the server struct, if need be, which it never will, and then an array pageRanks if it doesn’t exist. It will populate the third array element with a structure and set a key called data. The value of this will be a structure itself.

One thing to watch out for. If pageRanks does NOT exist yet, then array elements 1-2 will be null. ColdFusion doesn’t really like null array items. You can only check for them using try/catch. Again, there is a UDF at cflib.org just for stuff like this.

Sorry for being so long winded. If you found this item useful, please let me know!

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments