Advertisement
  1. Code
  2. PHP
  3. Yii

How to Program With Yii2: Using the Advanced Application Template

Scroll to top
Read Time: 9 min
This post is part of a series called How to Program With Yii2.
How to Program With Yii2: AuthClient Integration With Twitter & Google
How to Program With Yii2: Google Authentication
Final product imageFinal product imageFinal product image
What You'll Be Creating

If you're asking, "What's Yii?" check out Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of  Yii 2.0.

In this Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. As you begin to use Yii for real development, you may want to start your next project with its Advanced Application Template. Among other things, it provides integrated user management features as well as two applications, one for the consumer-facing front end and the other, an administrative back end.

In this tutorial, I'll introduce you to the Yii2 Advanced Template and guide you through the basic setup and usage. While Programming With Yii2: Integrating User Registration explored implementing user management on top of the basic template with the Yii2 User extension, this tutorial will launch a new repository with the advanced template rather than continue examples on our basic Yii hello codebase. 

Before we get started, please remember, I do try to participate in the discussions below. If you have a question or topic suggestion, please post a comment below or contact me on Twitter @reifman. You can also email me directly.

If you noticed there's been a delay in this series, it's because I'm recently back from brain surgery. Thank you for your patience and support—it's nice to be writing again regularly, and I'm looking forward to continuing coverage of Yii2.

How the Advanced Template Is Different

The most useful reason to migrate to the advanced template is for its implementation of user management features such as sign-up, sign-in, sign-out and password resets.

The advanced template also provides for multiple access trees for a larger web application. It has a front-end and back-end web application for end users and administrators. But, this could also be expanded—for example for moderators or a special API, though there are other ways to integrate these features in one application.

Here's a chart showing the primary differences between the basic vanilla Yii and the advanced installation:

Yii2 Advanced Template Comparison with Basic TemplateYii2 Advanced Template Comparison with Basic TemplateYii2 Advanced Template Comparison with Basic Template

In my latest tutorials about the Yii2 User extension, I'm increasingly impressed with its feature set as an alternative to the advanced template. However, it can also be easily integrated to either installation.

It's worth exploring the advanced template before you begin a major project. I'm about to help you do just that.

Installing the Advanced Template

Let's get started installing the advanced template with Yii2. We can follow the instructions at the advanced template project on GitHub.

Updating Composer

First, we'll ensure that composer has the packages it needs:

1
$ composer global require "fxp/composer-asset-plugin:~1.0.3"
2
3
Changed current directory to /Users/Jeff/.composer
4
./composer.json has been updated
5
Loading composer repositories with package information
6
Updating dependencies (including require-dev)
7
Nothing to install or update
8
Generating autoload files

Installing Yii With the Advanced Template

Then, we can install Yii with the advanced project template. We'll call our tutorial app yiiplus:

1
$ composer create-project --prefer-dist yiisoft/yii2-app-advanced yiiplus
2
Installing yiisoft/yii2-app-advanced (2.0.6)
3
  - Installing yiisoft/yii2-app-advanced (2.0.6)
4
    Loading from cache
5
6
Created project in yiiplus
7
Loading composer repositories with package information
8
Installing dependencies (including require-dev)
9
  - Installing yiisoft/yii2-composer (2.0.3)               
10
    Loading from cache
11
12
  - Installing ezyang/htmlpurifier (v4.6.0)
13
    Loading from cache
14
15
  - Installing cebe/markdown (1.1.0)
16
    Loading from cache
17
18
  - Installing bower-asset/jquery (2.1.4)
19
    Loading from cache
20
21
  - Installing bower-asset/jquery.inputmask (3.1.63)
22
    Loading from cache
23
24
  - Installing bower-asset/punycode (v1.3.2)
25
    Loading from cache
26
27
  - Installing bower-asset/yii2-pjax (v2.0.4)
28
    Loading from cache
29
30
  - Installing yiisoft/yii2 (2.0.6)
31
    Loading from cache
32
33
  - Installing swiftmailer/swiftmailer (v5.4.1)
34
    Loading from cache
35
36
  - Installing yiisoft/yii2-swiftmailer (2.0.4)
37
    Loading from cache
38
39
  - Installing yiisoft/yii2-codeception (2.0.4)
40
    Loading from cache
41
42
  - Installing bower-asset/bootstrap (v3.3.5)
43
    Loading from cache
44
45
  - Installing yiisoft/yii2-bootstrap (2.0.5)
46
    Loading from cache
47
48
  - Installing yiisoft/yii2-debug (2.0.5)
49
    Loading from cache
50
51
  - Installing bower-asset/typeahead.js (v0.10.5)
52
    Loading from cache
53
54
  - Installing phpspec/php-diff (v1.0.2)
55
    Loading from cache
56
57
  - Installing yiisoft/yii2-gii (2.0.4)
58
    Loading from cache
59
60
  - Installing fzaninotto/faker (v1.5.0)
61
    Loading from cache
62
63
  - Installing yiisoft/yii2-faker (2.0.3)
64
    Loading from cache
65
66
Writing lock file
67
Generating autoload files

Initializing Our Yii Application

Now, let's initialize our application: 

1
$ cd ~/Sites/yiiplus
2
$ php init
3
Yii Application Initialization Tool v1.0
4
5
Which environment do you want the application to be initialized in?
6
7
  [0] Development
8
  [1] Production
9
10
  Your choice [0-1, or "q" to quit] 0
11
12
  Initialize the application under 'Development' environment? [yes|no] yes

13


14
  Start initialization ...
15
16
   generate backend/config/main-local.php
17
   generate backend/config/params-local.php
18
   generate backend/web/index-test.php
19
   generate backend/web/index.php
20
   generate common/config/main-local.php
21
   generate common/config/params-local.php
22
   generate console/config/main-local.php
23
   generate console/config/params-local.php
24
   generate frontend/config/main-local.php
25
   generate frontend/config/params-local.php
26
   generate frontend/web/index-test.php
27
   generate frontend/web/index.php
28
   generate yii
29
   generate cookie validation key in backend/config/main-local.php
30
   generate cookie validation key in frontend/config/main-local.php
31
      chmod 0777 backend/runtime
32
      chmod 0777 backend/web/assets
33
      chmod 0777 frontend/runtime
34
      chmod 0777 frontend/web/assets
35
      chmod 0755 yii
36
      chmod 0755 tests/codeception/bin/yii
37
38
  ... initialization completed.

Prepare the Database

Next, I'll use MAMP's installed version of PHPMyAdmin to create the database:

create the database in PHPMyAdmincreate the database in PHPMyAdmincreate the database in PHPMyAdmin

Click Create. Taking screenshots for the tutorial, I forgot to click create and then wondered why I wasn't able to migrate my database—it didn't exist yet.

Next, edit /common/config/main-local.php to include your database settings:

1
<?php
2
return [
3
    'components' => [
4
        'db' => [
5
            'class' => 'yii\db\Connection',
6
            'dsn' => 'mysql:host=localhost;dbname=yiiplus',
7
            'username' => 'root',
8
            'password' => '-localmysqldevpwd-',
9
            'charset' => 'utf8',
10
        ],
11
        'mailer' => [

Then, you're ready to run the database migration to initialize your application. This primarily sets up the table for user management:

1
$ ./yii migrate
2
3
Yii Migration Tool (based on Yii v2.0.6)
4
5
Creating migration history table "migration"...Done.
6
Total 1 new migration to be applied:
7
    m130524_201442_init
8
9
Apply the above migration? (yes|no) [no]:yes
10
*** applying m130524_201442_init
11
    > create table {{%user}} ... done (time: 0.007s)
12
*** applied m130524_201442_init (time: 0.022s)
13
14
15
Migrated up successfully.

Configuring Apache for the Front-End and Back-End Sites

When we configure our development or production environment with the advanced template, we need to point the web server to a different root path, two actually. 

First, we'll edit our hosts file to include frontend.dev and backend.dev:

1
$ more /etc/hosts
2
3
127.0.0.1       localhost 
4
127.0.0.1       frontend.dev
5
127.0.0.1       backend.dev

In my development environment with MAMP, I'll link my yiiplus directory to MAMP's htdocs:

1
 $ cd /Applications/MAMP/htdocs/
2
 $ ln -s ~/Sites/yiiplus /Applications/MAMP/htdocs/yiiplus

Then, I'll activate (uncomment) the include for virtual hosts:

1
$ nano /Applications/MAMP/conf/apache/httpd.conf
2
3
# Virtual Hosts
4
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

And configure paths for each of my server names:

1
$ nano /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf
2
3
NameVirtualHost *:8888
4
5
<VirtualHost *:8888>
6
       ServerName frontend.dev
7
       DocumentRoot /Applications/MAMP/htdocs/yiiplus/frontend/web/
8
9
       <Directory "/Applications/MAMP/htdocs/yiiplus/frontend/web/">
10
           # use mod_rewrite for pretty URL support
11
           RewriteEngine on
12
           # If a directory or a file exists, use the request directly
13
           RewriteCond %{REQUEST_FILENAME} !-f
14
           RewriteCond %{REQUEST_FILENAME} !-d
15
           # Otherwise forward the request to index.php
16
           RewriteRule . index.php
17
18
           # use index.php as index file
19
           DirectoryIndex index.php
20
21
           # ...other settings...
22
       </Directory>
23
   </VirtualHost>
24
25
   <VirtualHost *:8888>
26
       ServerName backend.dev
27
       DocumentRoot /Applications/MAMP/htdocs/yiiplus/backend/web/
28
29
       <Directory "/Applications/MAMP/htdocs/yiiplus/backend/web/">
30
           # use mod_rewrite for pretty URL support
31
           RewriteEngine on
32
           # If a directory or a file exists, use the request directly
33
           RewriteCond %{REQUEST_FILENAME} !-f
34
           RewriteCond %{REQUEST_FILENAME} !-d
35
           # Otherwise forward the request to index.php
36
           RewriteRule . index.php
37
38
           # use index.php as index file
39
           DirectoryIndex index.php
40
41
           # ...other settings...
42
       </Directory>
43
   </VirtualHost>

Once that's complete, here's what the front-end website will look like at http://frontend.dev:8888:

Yii2 Advanced Template Front End Home PageYii2 Advanced Template Front End Home PageYii2 Advanced Template Front End Home Page

The back-end site will request that you log in—it's for administrators:

Yii2 Advanced Template Back End Home PageYii2 Advanced Template Back End Home PageYii2 Advanced Template Back End Home Page

Exploring User Management

Now I'm going to walk you through the basic user management features of the advanced template. But first we need to ensure we're receiving emails from Yii in our development environment.

Configuring Email Delivery

User management sends emails for password resets, so we need to activate Yii's SwiftMailer SMTP configuration. I'm going to use Mailtrap.io, which I explored in a prior tutorial, Introduction to Mailtrap: A Fake SMTP Server for Pre-Production Testing of Application Email.

Mailtrap provides a fake SMTP server for your development team to test, view and share emails sent from the pre-production environments and test with real data without the risk of spamming real customers. For many development tasks, using Mailtrap will be free.

Essentially, you sign up for Mailtrap and send all of your pre-production environment email via your fake Mailtrap SMTP server. Here's a short video overview of Mailtrap by Railsware:

If you follow the tutorial and create a Mailtrap account, you'll see your demo inbox:

The Mailtrap dashboard with your inboxesThe Mailtrap dashboard with your inboxesThe Mailtrap dashboard with your inboxes

And, when you click on the Settings icon in the inbox list, you'll see that each Mailtrap inbox has its own SMTP server credentials:

Mailtrap SMTP Server credentialsMailtrap SMTP Server credentialsMailtrap SMTP Server credentials

With Yii, I'm updating the SwiftMailer SMTP settings in /common/config/main-local.php. Here's what it may look like:

1
        'mailer' => [
2
                        'class' => 'yii\swiftmailer\Mailer',
3
                        'viewPath' => '@common/mail',
4
                        'useFileTransport' => false,
5
                        'transport' => [
6
                            'class' => 'Swift_SmtpTransport',
7
                            'host' => 'mailtrap.io',
8
                            'username' => '29xxxxxxxxxxx72',
9
                            'password' => '2c3xxxxxxxxxxf5',
10
                            'port' => '2525',
11
                            'encryption' => 'tls',
12
                                        ],
13
                    ],

Note that if you do not customize the viewPath as shown above, you may run into a bug around the email template files not being found.

Sign-Up and Registration

Here's what the front-end registration screen looks like:

Yii2 Advanced Application Template Sign up screenYii2 Advanced Application Template Sign up screenYii2 Advanced Application Template Sign up screen

It will land you on the home page in signed-in state:

Yii2 Advanced Application Template Signed inYii2 Advanced Application Template Signed inYii2 Advanced Application Template Signed in

Sign-In

Here's the sign-in screen:

Yii2 Advanced Application Template LoginYii2 Advanced Application Template LoginYii2 Advanced Application Template Login

Forgot Your Password

And here's the Forgot Your Password screen:

Yii2 Advanced Application Template Password ResetYii2 Advanced Application Template Password ResetYii2 Advanced Application Template Password Reset

If you ask for a new password, you'll find it within Mailtrap:

Yii2 Advanced Application Template Using MailTrap for SMTPYii2 Advanced Application Template Using MailTrap for SMTPYii2 Advanced Application Template Using MailTrap for SMTP

What's Next?

You may want to check out my Building Your Startup With PHP series, which uses Yii2's advanced template. Also, if you're interested in integrating this tutorial with Yii2 User, check out the guide to integrating Yii2 User with the advanced template and Google authentication (coming soon).

I hope you've enjoyed learning about the Yii2 Advanced Application Template. I'd be curious to hear your feedback in the comments on whether you prefer it to the basic template.

Watch for upcoming tutorials in my Programming With Yii2 series as I continue diving into different aspects of the framework. I welcome feature and topic requests. You can post them in the comments below or email me at my Lookahead Consulting website.

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. 

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.