marcosdipaolo / auth
一个 PHP 身份验证包
1.0.6
2024-02-25 01:59 UTC
Requires
- php: >=8.2
- ext-pdo: *
- marcosdipaolo/session: ^1.0
Requires (Dev)
- phpunit/phpunit: ^10.0
README
一个基本的 PHP 身份验证包
Auth 构造函数接收一个唯一的参数,即连接到您的应用程序数据库的 PDO 实例。
此连接对于验证凭证和注册用户是必要的。其他操作可以在不传递任何内容的情况下执行,例如登录或注销用户,检查是否有用户已登录,或获取已登录的用户。
登录和注销方法只是将用户放入或从 user 会话的键中放入或移除。为此,Auth 使用了 marcosdipaolo/session 包。
用法
配置
/** @var PDO $pdoInstance */ $auth = new MDP\Auth\Auth($pdoInstance); // Setting the users table name // The table the Auth package is going to interact with: $auth->setUsersTableName('members'); // default: 'users' // Setting the table fields the package should manage $auth->setEmailField('email_address'); // default: 'email' $auth->setPasswordField('pass'); // default: 'password' $auth->setUsernameField('alias'); // default: 'username' // You can do it in one time with the setUsersTableFields method $auth->setUsersTableFields([ 'usernameField' => 'username', 'passwordField' => 'password', 'emailField' => 'email' ]); // boolean, true if at least one field was set // Set the column that is going to be evaluated for logging in $auth->setLoginField('email'); // default: 'email'
登录和注册
要登录用户,必须使用登录方法,并将用户实例作为参数传递,该实例的类应实现 \MDP\Auth\Autheticatable 接口。
/** @var \MDP\Auth\Auth $auth */// boolean;v /** @var MDP\Auth\Authenticatable $user */ $auth->login($user); // logs in a user
这里检查凭证、注销、检查是否有已登录用户、获取已登录用户和注册。
/** @var \MDP\Auth\Auth $auth */ // check credentials $auth->check('yourField', 'youPassword'); // Register a user $auth->register('john_doe', 'john@doe.com', 'myPassword'); // bool (true if successful) $auth->logout(); // logs out whoever was logged in // Checks if there's someone logged in $auth->isUserLoggedIn(); // bool // Returns the logged user $auth->user(); // MDP\Auth\Authenticatable logged user | null
辅助函数 auth()
auth() 辅助函数返回 Auth 类的实例。
由于许多操作不需要连接到数据库,因此不需要传递 PDO 类的实例作为参数。
如果您需要执行需要数据库连接的操作,如 register 或 check,则需要传递 PDO 实例 auth($pdo)。