Using the User model

Let's start by having a look at how the User model is used in Yii.

You can open the file located at /models/User.php.

The first thing to notice is that the User class extends from a generic Yii Object class and implements IdentityInterface:

// User.php

namespace appmodels;

use yiiaseObject;
use yiiwebIdentityInterface;

class User extends Object implements IdentityInterface
{
    // ...

The yiiaseObject class is the parent class of all classes, which implements the concept of virtual attributes, with the use of dynamically invoked getters and setters, while yiiwebIdentityInterface provides the signature for methods we need to implement in our class to provide the authentication mechanism.

You will also notice by the private property $users that the model does not connect to a database; instead, it holds all the authentication data within the class itself. This has been done on purpose by the Yii developers, in order to have everything working without additional effort. This not only alleviates the problem of massive refactors in case you're not using any authentication in your app, but it's also a good starting point if you need to learn how the authentication works.

Authentication in Yii is not particularly straightforward, and a lot of the mechanism for authenticating a user is kept hidden from us; so, unless you need to implement some level of robustness in your application, you don't normally have to worry too much.

Instead, what is important to notice is that the authentication information is kept in an object, separate from the User model. This mechanism provides a separate and clean layer of security. From here, the authentication status is kept into a dynamically loaded class of the yiiwebUser type, which is accessible throughout the whole life of the application via Yii::$app->user. For instance, to check whether the user is logged in, we can do the following:

use Yii;

// check the user is logged in
if (!Yii::$app->user->isGuest) {
    // do something
}

This is actually used in several views, and it's clearly similar to what was happening before in Yii 1.

Having both static and private properties, as is the case with the $users variable in the User class, could make the job of testing our class quite hard, if not impossible, at times.

This is another reason why we need to modify the way it's defined entirely, and instead, the User class is extended from the ActiveRecord class and deals directly with the database. With this, we can make use of the fixtures that we can control without having to hardcode configuration settings or parameters in our tests, which could lead to unmaintainable tests, if not pointless ones.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset