Creating a new instance from CFC

Now this looks like something very straight forward, but it doesn't seem to be the case in ColdFusion. I need to instantiate the CFC from the inside as in var a = new this()

, but that obviously doesn't work. The CFC name cannot be used as it will be expanded, so I'm trying to hack the problem like this:

component {
    public function subQuery (required string table) {

        var classPath = getMetaData(this).fullname;
        return createObject("component", classPath).init(table, this.dsn);

    }
}

      

That would be acceptable, but the classpath returned from getMetaData(this).fullname

is incorrect. The CFC is in a folder named hypen as in my-folder

, and the returned path looks like my.-folder.myCFC

with a period inserted before a hyphen. Obviously I could manipulate this string with a Regex, but that's just not the road I want to go down on.

Hope someone has a cleaner approach, thanks.

+3


source to share


1 answer


You should be able to do this without any context for the object name in theory, since it will execute from within itself and it should check its current directory.

Therefore, the following task must be completed

var classPath = ListLast(getMetaData(this).fullname,'.');
return createObject("component", classPath).init(table, this.dsn);

      

So it doesn't matter what the directory names are and will work on any objects that propagate to it regardless of the directory structure, or for a complete example



public function cloneMe() {
    return CreateObject('component', ListLast(getMetaData(this).fullname,'.')).init(argumentCollection=arguments);
}

      

This way, any arguments passed will be passed to init. That is, extended CFC can override the method as follows (if you want errors when init arguments are not supplied)

public function cloneMe(required string table) {
    return super.cloneMe(table=arguments.table,dsn=this.dsn);
}

      

+4


source







All Articles