且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在 CakePHP 中使用 cookie 进行身份验证?

更新时间:2022-06-25 09:43:31

由于您的需求与 AuthComponent 最初的预期设计不符,因此您有两个选择.

Since your needs sound outwith AuthComponent's originally intended design you have two options.

首先,如果它真的不符合您的需求,您可以创建和维护您自己的 AuthComponent.为此,将 /cake/libs/controller/components/auth.php 复制到 /app/controller/components/auth.php.

Firstly, if it really doesn't fit your needs, you could create and maintain your very own AuthComponent. Do this by copying /cake/libs/controller/components/auth.php to /app/controller/components/auth.php.

这将允许您完全重写组件,但缺点是升级蛋糕时您将不再收到对 AuthComponent 的更新.

This would allow you to rewrite the component completely, but the downside is you will no longer receive updates to AuthComponent when you upgrade cake.

其次,您可以使用以下模式扩展 CakePHP 中的任何内容:

Secondly, you can extend just about anything in CakePHP using the following pattern:

// save as: /app/controllers/components/app_auth.php
App::import('Component', 'Auth');
class AppAuthComponent extends AuthComponent {
    function identify($user = null, $conditions = null) {
        // do stuff
        return parent::indentify($user, $conditions);
    }
}

.. 并用您的 AppAuthComponent 替换控制器中 AuthComponent 的所有实例.

.. and replace all instances of AuthComponent in your controllers with your AppAuthComponent.

  • 您只需要定义要替换的方法.
  • 您可以使用 parent::...
  • 方法参数应保持与原始 API 的顺序相同 保持一致性.
  • 如果您想添加更多方法参数,请将它们放在 API 参数之后,例如:

  • You only need to define the methods you wish to replace.
  • You can run methods from the original AuthComponent (even ones you have redefined) at any point during your methods using parent::...
  • The method arguments should remain in the same order as the original API for consistency.
  • If you wish to add more method arguments, put them after the API ones, eg:

function identify($user = null, $conditions = null, $custom = array()) { ... }

这种方法允许您进行特定于应用程序的自定义,同时在必要时仍使用核心中定义的最新方法.

This approach allows you to make application-specific customisation while still using the latest methods defined in the core where necessary.