这是艰难的一周的结束,因此很可能可以通过某种方式增强以下代码,但通常这种方法应该有效:
<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#">
我已将过程拆分为单独的变量并转储公共容器,只是为了便于阅读和理解此示例。
但无论如何,如果您可以在 Application.cfc 中使用动态映射,请使用它。
编辑:我添加了这样的示例,假设您在父文件夹中有以下 Application.cfc(例如,如果从 index.cfm 中查看,则为“../Application.cfc”):
<cfcomponent output="false">
<cfset this.mappings["/bin"] = getDirectoryFromPath(getCurrentTemplatePath()) & "bin/" />
</cfcomponent>
我的“路径转换”示例只是一个有趣的技巧和玩代码,这对于好的应用程序来说并不是真正简单的方法。