Advertisement
  1. Code
  2. Yii

How to Program With Yii2: Integrating User Registration

Scroll to top
Read Time: 8 min
This post is part of a series called How to Program With Yii2.
How to Program With Yii2: Working With the Database and Active Record
How to Program With Yii2: Localization With I18n
Final product imageFinal product imageFinal product image
What You'll Be Creating

If you're asking, "What's Yii?", check out my earlier tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.0, released October 12th, 2014.

This is part four of a series on Yii2. In Programming With Yii2: Getting Started, we set up Yii2 locally, built a Hello World application, set up a remote server, and used Github to deploy our code. In part two, we learned about Yii's implementation of its Model View Controller architecture and how to build web pages and forms that collect and validate data. In part three, we learned about working with databases and ActiveRecord. In this tutorial, we'll walk you through integrating a popular user registration plugin.

For these examples, we'll continue building on our hello app available in the Tuts+ repository so that you can follow along.

User Registration for Your Web Application

Almost any web application of any usefulness requires some form of user registration. Yii provides a couple of ways to approach user registration, both relatively straightforward. This is one of the things I like about using Yii over vanilla PHP—in moments, I can have a fully featured web application framework ready to build cool stuff on.

There are few reasons to rebuild the wheel and code user authentication and its many requirements and corollary features from scratch, e.g. sending emails and authentication for registration verification, password recovery, third party social authentication, et al. 

The Yii2 Advanced Application Template provides built-in user registration; we're using this approach in my Building Your Startup series. However, in this series, we've been building on Yii2's basic application template. The default basic application template includes hard coded user login, which isn't very useful.

Yii2 Basic Application Template Static LoginYii2 Basic Application Template Static LoginYii2 Basic Application Template Static Login

Another approach to user registration is to use third party extensions. For this tutorial, I'll walk you through using Dmitry Erofeev's Yii2-User extension. Documentation for Yii2-User is available here. Erofeev's building other plugins for Yii2 as well.

Dektriums Yii2-User DocumentationDektriums Yii2-User DocumentationDektriums Yii2-User Documentation

Installation of Yii2-User

Let's get started installing the Yii2-User extension. We'll follow the installation instructions.

Installing Yii2-User With Composer

First, we need to add Yii2-User to composer's required extensions. Edit the /composer.json file to include Yii2-User:

1
    "require": {
2
        "php": ">=5.4.0",
3
        "yiisoft/yii2": "*",
4
        "yiisoft/yii2-bootstrap": "*",
5
        "yiisoft/yii2-swiftmailer": "*",
6
        "dektrium/yii2-user": "*"
7
    },

Then, when we update composer, you'll see something like this:

1
Admins-MacBook-Pro-2:hello Jeff$ composer update
2
Loading composer repositories with package information
3
Updating dependencies (including require-dev)
4
  - Removing yiisoft/yii2-composer (2.0.0)                 
5
  - Installing yiisoft/yii2-composer (2.0.1)
6
    Downloading: 100%         
7
8
  ...
9
  
10
  - Installing dektrium/yii2-user (v0.8.2)
11
    Downloading: 100%         
12
13
Writing lock file
14
Generating autoload files

Update the Database

Next, we run the database migration for Yii2-User. This creates the database tables that the extension requires. These will manage user accounts and credentials.

1
hello Jeff$ php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations
2
Yii Migration Tool (based on Yii v2.0.1)
3
4
Total 6 new migrations to be applied:
5
    m140209_132017_init
6
	m140403_174025_create_account_table
7
	m140504_113157_update_tables
8
	m140504_130429_create_token_table
9
	m140830_171933_fix_ip_field
10
	m140830_172703_change_account_table_name
11
12
Apply the above migrations? (yes|no) [no]:yes
13
*** applying m140209_132017_init
14
    > create table {{%user}} ... done (time: 0.010s)
15
    > create unique index user_unique_username on {{%user}} (username) ... done (time: 0.015s)
16
    > create unique index user_unique_email on {{%user}} (email) ... done (time: 0.012s)
17
    > create unique index user_confirmation on {{%user}} (id, confirmation_token) ... done (time: 0.011s)
18
    > create unique index user_recovery on {{%user}} (id, recovery_token) ... done (time: 0.010s)
19
    > create table {{%profile}} ... done (time: 0.007s)
20
    > add foreign key fk_user_profile: {{%profile}} (user_id) references {{%user}} (id) ... done (time: 0.010s)
21
*** applied m140209_132017_init (time: 0.078s)
22
23
*** applying m140403_174025_create_account_table
24
    > create table {{%account}} ... done (time: 0.008s)
25
    > create unique index account_unique on {{%account}} (provider,client_id) ... done (time: 0.010s)
26
    > add foreign key fk_user_account: {{%account}} (user_id) references {{%user}} (id) ... done (time: 0.009s)
27
*** applied m140403_174025_create_account_table (time: 0.027s)
28
29
*** applying m140504_113157_update_tables
30
    > drop index user_confirmation ... done (time: 0.007s)
31
    > drop index user_recovery ... done (time: 0.008s)
32
    > drop column confirmation_token from table {{%user}} ... done (time: 0.009s)
33
    > drop column confirmation_sent_at from table {{%user}} ... done (time: 0.009s)
34
    > drop column recovery_token from table {{%user}} ... done (time: 0.007s)
35
    > drop column recovery_sent_at from table {{%user}} ... done (time: 0.008s)
36
    > drop column logged_in_from from table {{%user}} ... done (time: 0.007s)
37
    > drop column logged_in_at from table {{%user}} ... done (time: 0.008s)
38
    > rename column registered_from in table {{%user}} to registration_ip ... done (time: 0.009s)
39
    > add column flags integer NOT NULL DEFAULT 0 to table {{%user}} ... done (time: 0.010s)
40
    > rename column properties in table {{%account}} to data ... done (time: 0.008s)
41
*** applied m140504_113157_update_tables (time: 0.090s)
42
43
*** applying m140504_130429_create_token_table
44
    > create table {{%token}} ... done (time: 0.006s)
45
    > create unique index token_unique on {{%token}} (user_id,code,type) ... done (time: 0.010s)
46
    > add foreign key fk_user_token: {{%token}} (user_id) references {{%user}} (id) ... done (time: 0.009s)
47
*** applied m140504_130429_create_token_table (time: 0.026s)
48
49
*** applying m140830_171933_fix_ip_field
50
    > alter column registration_ip in table {{%user}} to bigint ... done (time: 0.010s)
51
*** applied m140830_171933_fix_ip_field (time: 0.011s)
52
53
*** applying m140830_172703_change_account_table_name
54
    > rename table {{%account}} to {{%social_account}} ... done (time: 0.001s)
55
*** applied m140830_172703_change_account_table_name (time: 0.002s)
56
57
Migrated up successfully.

Update the Configuration File

Next, we need to tell Yii to use the Yii2-User component. In /config/web.php, we replace the default User component...

1
        'user' => [
2
            'identityClass' => 'app\models\User',
3
            'enableAutoLogin' => true,
4
        ],

... with the Yii2-User component:

1
        'user' => [
2
            'class' => 'dektrium\user\Module',
3
            'enableUnconfirmedLogin' => true,
4
            'confirmWithin' => 21600,
5
            'cost' => 12,
6
            'admins' => ['admin']
7
        ],        

Activate the SwiftMailer

Since Yii2-User uses email to send out registration confirmations and forgotten passwords, it's time to activate our SwiftMailer configuration. In config/web.php, replace the default Mailer configuration here...

1
        'mailer' => [
2
            'class' => 'yii\swiftmailer\Mailer',
3
            // send all mails to a file by default. You have to set

4
            // 'useFileTransport' to false and configure a transport

5
            // for the mailer to send real emails.

6
            'useFileTransport' => true,
7
        ],

... with this—you'll need to include your own SMTP credentials:

1
        'mailer' => [
2
                'class' => 'yii\swiftmailer\Mailer',
3
                'viewPath' => '@app/mailer',
4
                'useFileTransport' => false,
5
                'transport' => [
6
                    'class' => 'Swift_SmtpTransport',
7
                    'host' => 'your-host-domain e.g. smtp.gmail.com',
8
                    'username' => 'your-email-or-username',
9
                    'password' => 'your-password',
10
                    'port' => '587',
11
                    'encryption' => 'tls',
12
                                ],
13
            ],

Integration of Yii2-User

Now, we need to link our navigation bar to the Yii2-User controller paths. In /views/layouts/main.php, we update the navigation bar array definition for the Bootstrap menu. Replace the current navigation bar...

1
echo Nav::widget([
2
                'options' => ['class' => 'navbar-nav navbar-right'],
3
                'items' => [
4
                    ['label' => 'Home', 'url' => ['/site/index']],
5
                    ['label' => 'Status', 'url' => ['/status/index']],
6
                    ['label' => 'About', 'url' => ['/site/about']],
7
                    ['label' => 'Contact', 'url' => ['/site/contact']],
8
                    Yii::$app->user->isGuest ?
9
                        ['label' => 'Login', 'url' => ['/site/login']] :
10
                        ['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
11
                            'url' => ['/site/logout'],
12
                            'linkOptions' => ['data-method' => 'post']],
13
                ],
14
            ]);

... with the following array definition:

1
            $navItems=[
2
                ['label' => 'Home', 'url' => ['/site/index']],
3
                ['label' => 'Status', 'url' => ['/status/index']],
4
                ['label' => 'About', 'url' => ['/site/about']],
5
                ['label' => 'Contact', 'url' => ['/site/contact']]
6
              ];
7
              if (Yii::$app->user->isGuest) {
8
                array_push($navItems,['label' => 'Sign In', 'url' => ['/user/login']],['label' => 'Sign Up', 'url' => ['/user/register']]);
9
              } else {
10
                array_push($navItems,['label' => 'Logout (' . Yii::$app->user->identity->username . ')',
11
                    'url' => ['/site/logout'],
12
                    'linkOptions' => ['data-method' => 'post']]
13
                );
14
              }
15
            echo Nav::widget([
16
                'options' => ['class' => 'navbar-nav navbar-right'],
17
                'items' => $navItems,
18
            ]);

Reload the application and click the Sign Up link in the navigation bar. You should see something like this:

Yii2-User Sign Up PageYii2-User Sign Up PageYii2-User Sign Up Page

When you click Sign Up, you'll see the confirmation notification. This tells us an email has been sent that we need to click on to verify our registration.

Yii2-User Sign Up Confirmation NoticeYii2-User Sign Up Confirmation NoticeYii2-User Sign Up Confirmation Notice

You'll receive an email much like this one:

Yii2-User Confirmation EmailYii2-User Confirmation EmailYii2-User Confirmation Email

Click on the link in the email and you'll see something like this:

Yii2-User Sign Up ConfirmationYii2-User Sign Up ConfirmationYii2-User Sign Up Confirmation

Notice the login state maintained by Yii2 and the Yii2-User component—it's displayed in the navigation bar above. Click Logout and let's walk through the Sign In page:

Yii2-User Sign In FormYii2-User Sign In FormYii2-User Sign In Form

Yii2-User also includes password recovery:

Yii2-User Forgot Your PasswordYii2-User Forgot Your PasswordYii2-User Forgot Your Password

Just like that, we have a hugely important core authentication component for our application.

Yii2-User also has a number of configuration features which you can explore further on your own, e.g. third party social authentication. We'll likely return to them in a later tutorial.

What's Next?

I hope you've found this useful for your own Yii2 web application. If you'd like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page. My instructor page will include all the articles from this series as soon as they are published.

Related Links

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.