Answer the question
In order to leave comments, you need to log in
Yii2 and DAO. Am I going right?
Hello. Being in the process of studying the framework, I decided to change the registration from ActiveRecord to Database Access Objects. In principle, I did it and everything works, but the question is, am I doing it right at all ?? Since there are not so many similar examples on the network, it’s clear that no one would even think of doing registration / authorization on the DAO, but still ...
In the controller, I describe the standard method:
public function actionRegister() {
$model = new RegForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($user = $model->reg()) {
echo '<pre>'; print_r($user); echo '</pre>';
} else {
echo 'Register Error';
}
}
return $this->render('reg', ['model' => $model]);
}
public function rules() {
return [
// ...
['email', 'checkEmail'],
// ...
];
}
public function checkEmail($attribute) {
if (User::checkEmail($this->email))
$this->addError($attribute, 'Эта почта уже занята!!!');
}
public function checkEmail($email) {
$db = Yii::$app->db;
$check = $db->createCommand('SELECT COUNT(*) FROM {{%user}} WHERE email=:email')
->bindValue(':email', $email)
->queryOne();
return $check['COUNT(*)'];
}
public function reg() {
return User::add($this->email, $this->password, $this->action);
}
public function add($email, $password, $action = 'Y') {
$db = Yii::$app->db;
$db->createCommand()->insert('{{%user}}', [
'action' => $action,
'email' => $email,
'password_hash' => Yii::$app->security->generatePasswordHash($password),
'auth_key' => Yii::$app->security->generateRandomString(),
'create_at' => date('Y-m-d H:i:s')
])->execute();
$ress = $db->createCommand('SELECT * FROM {{%user}} WHERE email=:email')
->bindValue(':email', $email)
->queryOne();
return $ress;
}
SELECT COUNT(*) FROM `bav_user` WHERE email='[email protected]'
SHOW FULL COLUMNS FROM `bav_user`
SHOW CREATE TABLE `bav_user`
INSERT INTO `bav_user` (`action`, `email`, `password_hash`, `auth_key`, `create_at`) VALUES ('Y', '[email protected]', '$2y$13$qZC4jOM0gLG7vgvWU8t0keENXlnYFzoetrsFzQpkavwktootfD.Rq', 'RuHh8UQK5V16FsEKSxZPLvSLQNhw-xCU', '2015-07-19 00:10:08')
SELECT * FROM `bav_user` WHERE email='[email protected]'
Answer the question
In order to leave comments, you need to log in
on the DAO, no one would even think of it,
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question