Difference between #1 and #4 of
Using multiple models in an identity

Changes

Title unchanged

Using multiple models in an identity

Category unchanged

How-tos

Yii version unchanged

2.0

Tags changed

authentication,identity

Content changed

[...]
private $_authkey;
private $_passwordHash;

public static function findIdentity($id)
{
     // We are going to login, so `$id` will be an empty string
 
        // `if (\count($parts) !== 2)` will raise an error because the parameter $id is empty
 
        if (strlen($id) === 0) {
 
            return null;
 
        }
 
        
 
$parts = explode('-', $id);
if (\count($parts) !== 2) {
throw new InvalidCallException('id should be in form of Type-number');
[...]
{
return password_verify($password, $this->_passwordHash);
}
 
    
 
    public static function findByUsername(username)
 
    {
 
        $model = Customer::find()->where(['username' => $username])->one();
 
        if (!$model) {
 
            $model = Supplier::find()->where(['username' => $username])->one();
 
        }
 
 
        if (!$model) {
 
            return false;
 
        }
 
 
        if ($model instanceof Customer) {
 
            $type = self::TYPE_CUSTOMER;
 
        } else {
 
            $type = self::TYPE_SUPPLIER;
 
        }
 
 
        $identity = new Identity();
 
        $identity->_id = $type . '-' . $model->id;
 
        $identity->_authkey = $model->authkey;
 
        $identity->_passwordHash = $model->password_hash;
 
        return $identity;
 
    }


public static function findIdentityByEmail($email)
[...]
In the above we assume that our ids are like `customer-23` or `supplier-34`. When we need to get identity instance we split the id by `-` and getting both type and integer id for the model corresponding to that type.

Having identity we can tell Yii to use it via `confi
ng/main.php`:

```php
[...]
{
if ($this->_user === false) {
$this->_user = Identity::find
IdentityByEmailByUsername($this->username);
}

return $this->_user;
}
}
[...]
9 2
5 followers
Viewed: 36 782 times
Version: 2.0
Category: How-tos
Written by: samdark
Last updated by: Néstor Acevedo
Created on: Oct 7, 2018
Last updated: 3 months ago
Update Article

Revisions

View all history