cpliakas / doctrine-password
为 Doctrine 添加一个密码类型,使用 phpass 库来散列和比较密码。
1.0.0
2013-06-16 19:01 UTC
Requires
- php: >=5.3.0
- doctrine/orm: ~2.0
- rych/phpass: ~2.0
This package is auto-updated.
Last update: 2024-08-25 12:14:50 UTC
README
本项目为 Doctrine 提供了一个密码类型,自动使用 PHP 密码库 散列密码,并提供了一个辅助方法来比较用户提交的原始数据。主要目标是使在数据库中存储散列密码和验证用户提交的密码变得简单。
安装
可以使用 Composer 安装此库。在项目中的 composer.json
文件中定义以下需求
{ "require": { "cpliakas/doctrine-password": "*" } }
然后按照 Composer 的 安装/使用 指南安装此库。
使用方法
此库假设开发者熟悉 Doctrine ORM,否则下面的代码片段可能不会很有意义。
首先,定义您的实体。对于存储密码的列使用 "password" 类型
<?php // src/User.php /** @Entity **/ class User { /** * @Id @Column(type="integer") * @GeneratedValue(strategy="IDENTITY") */ private $id; /** @Column(length=255, unique=true, nullable=false) **/ private $email; /** @Column(type="password", nullable=false) **/ private $password; public function setEmail($email) { $this->email = $email; } public function setPassword($password) { $this->password = $password; } public function getPassword() { $return this->password; } }
然后编写代码以 获取 EntityManager,并注册密码类型
<?php // bootstrap.php use Doctrine\DBAL\Types\Type; require_once 'vendor/autoload.php'; // .. (code to obtain the entity manager, refer to the Doctrine docs) Type::addType('password', 'Cpliakas\Password\Doctrine\PasswordType');
接下来,配置命令行工具 并使用它来创建您的模式
php vendor/bin/doctrine orm:schema-tool:create
现在您可以为系统添加用户了。以下示例中我们将设置原始密码,库将在写入数据库时自动散列它。
<?php // Replace with your own project's bootstrap file. require_once 'bootstrap.php'; // Replace with your project's mechanism to retrieve the EntityManager. $em = GetEntityManager(); $user = new User(); $user ->setEmail('myuser@example.com') ->setPassword('mypassword') ; $em->persist($user); $em->flush();
密码现在以散列形式存储在数据库中。当从数据库检索用户时,密码以包含比较用户提交的原始密码的辅助方法的对象返回
<?php // Replace with your own project's bootstrap file. require_once 'bootstrap.php'; // Replace with your project's mechanism to retrieve the EntityManager. $em = GetEntityManager(); $repository = $em->getRepository('User'); $user = $repository->findOneBy(array('email' => 'myuser@example.com')); // Returns true. $user->getPassword()->match('mypassword'); // Returns false. $user->getPassword()->match('badpassword');