Blog
Dev Tips & Tricks

How to Work with Yii 2 Config Kit and Yii 2 Usuario Module

June 15, 2017
6 min read
Working With Yii 2 Config Kit and Yii 2 Usuario Module - Featured Image
By
Antonio Ramirez Cobos

Step 1. Install Boilerplate

As you probably know by now, when developing on PHP, Composer has become one of our best and must have allies for us. Therefore, I am assuming that you have it installed globally on your computer (if you haven't yet, I highly recommend you to do it).

For the sake of this article and to make things easier, I have created a new Yii 2 application boilerplate project and submitted to Packagist. This boilerplate has already configured everything we need on this tutorial but do not worry, I would still explain what was done and what is different from Yii 2 Application Template.

Having the boilerplate on Packagist, the way to start a new project is as easy as to use Composer's create-project command:

1$ composer create-project --prefer-dist --stability=dev 2amigos/yii2-app-usuario-template my-app
2$ cd my-app

If everything goes well, the command would have placed our boilerplate into the my-app folder (name that we have chosen for the example). But let's look on certain lines displayed when the command was executed:

1...
2> php -r "file_exists('.env') || copy('.env.example', '.env');"
3... 
4> yii\composer\Installer::postCreateProject
5chmod('runtime', 0777)...done.
6chmod('public/assets', 0777)...done.
7chmod('yii', 0755)...done.
8> php yii post-install/generate-cookie-validation

Those lines mean that the composer create-project command did not simply started a project structure for us, the boilerplate contains specific instructions to:

  • create a .env environment file where global settings are written
  • create all required writable folders for Yii to work properly on runtime (thanks to Yii 2)
  • and generate the cookieValidationKey for us

How this boilerplate does it? To get the answer we need to look carefully on the composer.json file located on our root, specifically on its scripts section:

1 "scripts": {
2    "post-root-package-install": [
3        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
4    ],
5    "post-create-project-cmd": [
6        "yii\\composer\\Installer::postCreateProject",
7        "php yii post-install/generate-cookie-validation"
8    ],
9    "start-test-server": [
10        "php -r \"file_exists('public/index-test.php') || copy('tests/_support/index-test.php', 'public/index-test.php');\"",
11        "php tests/bin/yii serve --docroot=@web"
12    ],
13    "stop-test-server": [
14        "php -r \"unlink('public/index-test.php');\"",
15        "kill $(lsof -ti tcp:8080)"
16    ],
17    "start-server": [
18        "php yii serve --docroot=@web"
19    ],
20    "stop-server": [
21        "kill $(lsof -ti tcp:8080)"
22    ]
23},

The scripts section is where we configure the scripts for composer. As you can see, in our composer.json we have configured not only two of Composer events but also four commands that you'll see how we are going to make use of them later. The post-create-project-cmd makes use of app\commands\PostInstallController class.

For further information regarding the configuration options of this Composer section, please visit its guide.

Step 2. Configure Your Application

The boilerplate comes with the Yii 2 Usuario Module and Yii 2 Config Kit already configured as required packages in our composer.json file and also the required ConfigurationBuilder for the Application to run. I highly recommend you to check the code of src/App/Configuration/ConfigurationBuilder.php file, so you can see how useful the config kit is so you can build your very own application structure to work with Yii 2.

Database Configuration

Go to the .env file located at the root of your application and modify the following variables:

1DATABASE_DSN_BASE = "mysql:host=localhost;port=3306" 
2DATABASE_DSN_DB = "yii2_app"
3DATABASE_USER = "root"
4DATABASE_PASSWORD = ""
5DATABASE_TABLE_PREFIX = ""
6DATABASE_CHARSET = "utf8"

To configure the database for your tests, you will have to do the same but on env.test file instead.

Step 3. AuthManager Configuration

Prior to execute the migrations of Yii 2 Usuario Module we have to add its Authorization Manager component so we can install the RBAC migrations. We want it to be configured on both console and web components:

Step 4. Run Migrations

Before we start, Yii 2 Usuario Module has its migration classes with namespaces. That means we should configure Application's controllerMap::migrate::migrationNamespaces attribute, a feature that was included since Yii 2 version 2.0.10.

If you do not wish to use them like we are going to explain right now, simply copy the classes of vendor/2amigos/yii2-usuario/src/User/Migration to the app/migrations folder and remove its namespace Da\User\Migration. After that simply execute $ ./yii migrate/up and will collect the migrations of that folder.

The configuration of it is within config/console/app.php:

1// ... 
2'controllerMap' => [
3    'migrate' => [
4        'class' => \yii\console\controllers\MigrateController::class,
5        'migrationNamespaces' => [
6            'Da\User\Migration',
7        ],
8    ],
9],
10//...

Now when we run the migrations, we will see the following list:

1$ ./yii migrate
2Yii Migration Tool (based on Yii v2.0.12)
3
4Creating migration history table "migration"...Done.
5Total 4 new migrations to be applied:
6    Da\User\Migration\m000000_000001_create_user_table
7    Da\User\Migration\m000000_000002_create_profile_table
8    Da\User\Migration\m000000_000003_create_social_account_table
9    Da\User\Migration\m000000_000004_create_token_table
10
11Apply the above migrations? (yes|no) [no]:

Obviously, we write yes and migrations will be applied. Next, we need to run Yii's RBAC migrations:

1$ ./yii migrate --migrationPath=@yii/rbac/migrations

Step 5. Configure Usuario Module

Its time to configure Yii 2 Usuario Module. And we need to do it in two places:

The configuration in config/console/modules/user.php is simple, we just need to configure the class to the module:

1<?php
2
3return [
4
5    /*
6    * --------------------------------------------------------------------------
7    * Dos Amigos User Module
8    * --------------------------------------------------------------------------
9    *
10    * Implements User Management Module configuration
11    */
12
13    'class' => 'Da\User\Module'
14];
We do this so our Yii's console application can find the useful console commands that comes with the module and we need them on our next step.

The configuration of the module on config/web/components/authManager.php is different, here we should configure the module according to our needs. The module comes with a huge list of configuration options.

Step 6. Create Your Demo Admin User

Before we use the application, lets create our demo admin user so we can login to our backend. As said, the module comes with a list of handy  console commands. We just need two but you should check them all out.

1$  ./yii user/create demo@example.com username mypassword
2$ ./yii user/confirm demo@example.com

Now, to allow this user to be one of the administrators, let's add the username selected (on the example above is username) to the config/web/modules/user.php file:

1<?php
2
3return [
4
5    /*
6    * --------------------------------------------------------------------------
7    * Dos Amigos User Module
8    * --------------------------------------------------------------------------
9    *
10    * Implements User Management Module configuration
11    */
12
13    'class' => 'Da\User\Module',
14    'enableRegistration' => false,
15    'administrators' => ['username'] // add the username of the test user here!
16];
That configuration is good for local development purposes. Nevertheless, for production I highly recommend that you create your very own custom command that will install all the roles, permissions and necessary initial users to run the application the first time.

Step 7. Running Your Application

Remember our composer scripts configuration? Well, time to use some of the commands. Run the following at the root of your application:

$ composer start-server

Now, visit localhost:8080 on your browser, you should see something like the following:

Go ahead, try to login with the previously created user. The user module has integrated all you need to manage your users, roles, permissions and integrates your login, recover, reset, register processes.

If you wish to stop running the server, open a new terminal window and type: $ composer stop-server.

References

2am.tech can help you build your next Yii2 framework project. Have a need or an idea? Get in touch and let’s talk.

Accelerate Your Career with 2am.tech

Join our team and collaborate with top tech professionals on cutting-edge projects, shaping the future of software development with your creativity and expertise.

Get Started

Don't miss out on
our latest insights
– Subscribe Now!

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Share This Post
Back to Blog
Don't miss out on
our latest insights
– Subscribe Now!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Navigate
Start Now