2011-12-03 26 views
1

我想添加一个可以被插件中的所有函数访问的变量,但我得到一个变量未定义的错误。这里是我的插件:如何范围一个变量,使其可用于同一CFC中的其他功能(CFWheels插件)?

component 
    mixin="Controller" 
{ 
    public any function init() { 
     this.version = "1.0"; 
     return this; 
    } 

    public void function rememberMe(string secretKey="rm_#application.applicationName#") { 
     this.secretKey = arguments.secretKey; 
    } 

    public void function setCookie(required string identifier) { 
     // Create a cookie with the identifier and encrypt it using this.secretKey 
     // this.secretKey is not available, though, and an error is thrown 
     writeDump(this.secretKey); abort; 
    } 
} 

我所说的插件从我Sessions.cfc控制器:

component 
    extends="Controller" 
{ 
    public void function init() { 
     // Call the plugin and provide a secret key 
     rememberMe("mySecretKey"); 
    } 

    public void function remember() { 
      // Call the plugin function that creates a cookie/I snipped some code 
      setCookie(user.id); 
     } 
} 
  1. 当我倾倒this.secretKey插件里面,我得到一个变量未定义的错误。该错误告诉我,this.secretKey不可用于Sessions.cfc控制器。但是我不是从Sessions.cfc转储,我从插件的CFC中倾销,如您所见。为什么?

  2. 我怎样才能在我的插件范围this.secretKey,以便它可以通过setCookie()访问?到目前为止,variablesthis都失败了,无论我是在函数,伪构造函数还是init()中添加定义。为了好的措施,我扔了variables.wheels.class.rememberME,无济于事。

这里的错误:

Component [controllers.Sessions] has no acessible Member with name [secretKey] 
+0

请发布您使用的CFML a)调用init()和b)调用remember()。 –

回答

2

你在做什么在init()不会在production模式下工作。控制器的init()仅在该控制器的第一个请求上运行,因为在此之后它会被缓存。

因此this.secretKey将在该控制器的第一次运行中设置,但从不会在后续运行中设置。

你有几个选项,使这项工作...

I.使用伪构造函数,它不会在每个控制器要求运行:

component 
    extends="Controller" 
{ 
    // This is run on every controller request 
    rememberMe("mySecretKey"); 

    // No longer in `init()` 
    public void function init() {} 

    public void function remember() { 
     // Call the plugin function that creates a cookie/I snipped some code 
     setCookie(user.id); 
    } 
} 

II。使用之前的过滤器来呼吁每个请求:

component 
    extends="Controller" 
{ 
    // No longer in `init()` 
    public void function init() { 
     filters(through="$rememberMe"); 
    } 

    public void function remember() { 
     // Call the plugin function that creates a cookie/I snipped some code 
     setCookie(user.id); 
    } 

    // This is run on every request 
    private function $rememberMe() { 
     rememberMe("mySecretKey"); 
    } 
} 

三。将密钥存储在持久范围内,以便从控制器的init()只调用一次即可。

component 
    mixin="Controller" 
{ 
    public any function init() { 
     this.version = "1.0"; 
     return this; 
    } 

    public void function rememberMe(string secretKey="rm_#application.applicationName#") { 
     application.secretKey = arguments.secretKey; 
    } 

    public void function setCookie(required string identifier) { 
     // This should now work 
     writeDump(var=application.secretKey, abort=true); 
    } 
} 
+0

谢谢,这就是我最终做的。然后我决定放弃,因为确保一个“记住我”系统是一个痛苦的屁股,它应该使用额外的分贝列来完成。这使得它成为一个可怕的插件候选人。所以,毕竟没有记住我的插件 - 我只有在我完成了该死的事情之后才意识到这一点。每日一词:研究! – Mohamad

相关问题