In Coldfusion, how do I init a component that is located above the current path folder?

if you have the Application.cfc in the root of your folder structure, you could use something like this:

<cfset this.mappings["/local"] = getDirectoryFromPath(getCurrentTemplatePath()) />

and then access it through "local.bin.myComponent"


We handle this using a mapping in the cf administrator. Usually all of the components go in one directory which is above the www root. In your case you could add a mapping to / which would allow you to do:

myService = createObject("component", "mymapping.bin.myComponent");

It is an end of the hard week, so pretty likely that following code can be enhanced somehow, but generally this approach should work:

<cfscript>

    // this script is here http://XXXXXXX/test/paths/relative/reports/index.cfm
    // component is here http://XXXXXXX/test/paths/relative/bin/myComponent.cfc

    local = {};

    // initialize with dynamic mapping
    local.myComponentDynamic = createObject("component", "/bin/myComponent");

    // grab the current directory name
    local.parentPathExpanded = ExpandPath("../");
    local.scriptPathExpanded = ExpandPath(cgi.SCRIPT_NAME);
    local.thisDirectory = GetDirectoryFromPath(Replace(local.scriptPathExpanded, local.parentPathExpanded, ""));

    // build base path
    local.scriptPathDirectory = GetDirectoryFromPath(cgi.SCRIPT_NAME);
    local.basePath = Replace(local.scriptPathDirectory, local.thisDirectory, "");

    // this is relative path we already know
    local.relativePath = "bin/myComponent";

    // initialize with slash-syntax (path starting with /)
    local.myComponentSlash = createObject("component", local.basePath & local.relativePath);

    // convert path to the dot-syntax
    local.dottedPath = Replace(local.basePath & local.relativePath, "/", ".", "ALL");
    local.dottedPath = Right(local.dottedPath, Len(local.dottedPath)-1);

    // initialize with dot-syntax path
    local.myComponentDot = createObject("component", local.dottedPath);

</cfscript>
<cfdump var="#local#">

I've split the process into the separate variables and dumped the common container just to make it easy to read and understand this example.

But any way, if you can use dynamic mapping in Application.cfc -- use it.

EDIT: I've added such example, assuming you have following Application.cfc in the parent folder (e.g. "../Application.cfc" if looking from the index.cfm):

<cfcomponent output="false">

    <cfset this.mappings["/bin"] = getDirectoryFromPath(getCurrentTemplatePath()) & "bin/" />

</cfcomponent>

My "paths-converting" example is just a fun trickery and playing with code which not really straightforward approach for good applications.

Tags:

Coldfusion

Cfc