无法从CakePHP 2.x中的控制器到期cookie

usu*_*oio -2 php api cookies cakephp cakephp-2.0

我正在CakePHP中构建一个API.我有一个功能,作为其执行的一部分首先破坏与会话相关的cookie.我使用以下代码来执行此操作.

public function new_thing () {

    // I first call another controller to use functions from that controller
    App::import('Controller', 'Person');    
    $PersonsController = new PersonsController;

    // This function call is the problem
    // This does not throw any errors but does not destroy the cookie as requested
    $PersonsController->_kill_auth_cookie()

}


// This is from the Person controller, these are the functions used in the API

// This is the function that sets the cookies
public function _set_auth_cookie( $email ) {
    setcookie(Configure::read('auth_cookie_name'), $email);
}

// this is the function that does not properly destroy the cookie from the API
// interestingly, it does work when called from in this controller
public function _kill_auth_cookie() {
    setcookie(Configure::read('auth_cookie_name'), 'xxx', time()-7200);
}
Run Code Online (Sandbox Code Playgroud)

我无法让API正确地使会话中先前创建的cookie过期,我不知道为什么.另外 - 令人抓狂的是,日志是空的,没有任何错误被抛出,所以我不知道接下来该做什么.

bur*_*zum 6

这段代码和概念有很多错误......

  • 不要在任何地方实例化控制器.这是完全错误的,被设计破坏并违反了MVC模式.框架本身应根据请求仅调度一个控制器; 你不要手动实例化它们.
  • 使用Cookie的API?好吧,并非不可能,但绝对不能与之合作.这是可能的,但我从来没有在野外见过.我为那个必须实施它的人感到难过.看到这个问题.
  • 你为什么不使用CookieComponent?它有一个内置的destroy()方法来删除cookie.
  • 如果您有"auth"cookie,为什么不使用CakePHP的内置Auth系统?它将处理所有这些.
  • App::uses()不要App::import()在这里使用
  • 按照惯例,只有受保护的函数应该以前缀为前缀 _

第一点很可能是cookie和会话混乱的原因,因为第二个控制器实例再次启动组件,并且这个cookie和会话也可能是第二次.然而,这可能导致"有趣的"副作用.

我首先调用另一个控制器来使用该控制器的功能

这证明您的架构被设计破坏了.需要在其他地方执行的代码; 在这种情况下应该采用模型方法.或者至少是一个组件,如果有不同控制器之间共享控制器相关的东西.