GrabDuck

How to Start Development of a Large Project With Yii2 - DZone Web Dev

:

Selection of the Back-End Platform

To develop a high-quality, easily scalable Web app with great performance, you need to select a development platform that pays attention to multiple factors. You should do it as soon as you have received complete information about the tasks ahead.

In the case of my project, one of the most important factors was the app’s ability to perform under heavy load. In other words, I had a clear task to guarantee excellent performance of the service under any condition.

There are lots of instruments on the market that can help us support the app’s performance and stability under stressful conditions and, to tell the truth, I used several of these instruments in development. Yet, I decided to opt for Yii2.

Using the Yii2 framework has the following benefits:

  • High performance

  • Ease of using various databases

  • Support of page and element caching

  • Error trapping and management

  • Enabled authentication and authorization

  • Efficient developer cooperation due to ease of database migration

Having installed an advanced template, I got immediate access to a number of features we needed (e.g. built-in user registration forms with enabled password recovery). Yet, the most important advantage of utilizing this template is that it includes frontend and backend components.

When I was designing the app’s structure, I arrived at the decision that its logical ports should be divided into several modules. Although modules tend to be hooked on one another, modular programming allows us to efficiently add and support the code.

Selection of the Front-End Platform

As the application supports a whole bunch of interactive control elements which need to be communicating with each other, I decided that JQuery should be reinforced by adding AngularJS to the frontend. It allows us to perform templating without wrecking the structure of the HTML document.

By doing so, we can convert everything to HTML first and then add template attributes. An HTML layout tool will be able to continue its operations as if it was a static HTML document. In other words, you can easily alter the design within the development process. You are not dependant on a fixed layout, class attributes, or IDs of HTML elements. It gives you an edge if you want to share the UI development process between several team members. We took advantage of that feature: the first member of the team was busy with the layout, while the second one was pushing in with bindings and adding viewmodel to the backend.

Here are several benefits of using AngularJS:

  • Relative ease of use and adaptation

  • Interaction and dependency chains are easy to create

  • Enables team cooperation

  • Extensive usage of HTML attributes with minimum Javascript code

  • Excellent support from the community

  • REST is simple to use

  • Development of the Modular Structure

I hope that you are quite familiar with Yii2 and have developed at least several apps utilizing this powerful framework. From now on I will focus only on the solutions that we have applied while developing the application.

As I’ve mentioned before, we opted to use an advanced template. At the very first step, most users have the difficulty with installation of yii2-app-advanced using the composer. It they try to open the website in the browser, the following error is displayed: The file or directory to be published does not exist: D:\OpenServer\domains\yii2-app-advanced/vendor\bower/jquery/dist

1.png

It is necessary to install a composer asset plugin and solve the aforementioned problem using the commands below:

cd /path/to/your/project

composer global require "fxp/composer-asset-plugin:~1.1"

composer update

Also, check out if you have the following code in your composer.json file:

{   
   "extra": {
       "asset-installer-paths": {
           "npm-asset-library": "vendor/npm",
           "bower-asset-library": "vendor/bower"
       }
   }
}

I’ve organized the app’s modular structure as well. First off, you need to add an alias for the module folder into \common\config\bootstrap.php file:



Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('@modules', dirname(dirname(__DIR__)) . '/modules');

Now, all modules that we are going to create will be automatically placed into the /modules folder.

It is time to create the first module of our project. Let’s start with a module that will display the main pages of the website: Homepage, Contact page, 404 Error page, and About us. For this, we can use the Gii code generator that can write code for you.

Access the Gii generator’s homepage.

2.png

On the current stage of the development process, most likely you have already created the project’s database and set it up to add \environments\dev\common\config\main-local.php configuration file.

…
  'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=your-db-name',
            'username' => 'db-user-name',
            'password' => 'db-user-password',
            'charset' => 'utf8',
        ],
…

Press the Start button in the Module Generator to get access to this view.

Fill in the inputs as shown below:

Module Class:
modules\site\Module
Module ID:
site

Add the following string of code to \common\config\main.php file:

......
   'modules' => [
       'site' => [
           'class' => 'modules\site\Module',
       ],
   ],
   ......

Then, edit the frontend configuration file \frontend\config\main.php by adding the following line of code:

......
   'defaultRoute' => 'site/site/index',
   ......

Then, delete the following string of code in the file:

'controllerNamespace' => 'frontend\controllers'

You should do it because every module will define its namespaces for controllers now. Let’s talk about it more.

As we want our modules to be non-reliant on each other and used multiple times in different projects (add this module or delete that one), we will support not only all front-end but also admin content management features in our module. Thus, we will save controllers, models, and views for every module in different catalogues. The catalogues will have the following structure:

…
site
-- controllers
-- -- backend
-- -- frontend
-- models
    -- -- backend
    -- -- frontend
    -- views
    -- -- backend
    -- -- frontend
…

After that, you need to move controllers and views that we already have in the module to the corresponding frontend folders, and don’t forget to change the namespace in the controller to namespace modules\site\controllers\frontend;

We will rewrite the module’s code so that it was clear which controller, when working with the frontend or with the admin, it needs to refer to. In other words, when we deal with the frontend part, it will refer to the controller in the /modules/site/controllers/frontend folder. But when we access the admin part, it will refer to the /modules/site/controllers/backend folder.

Here's how it looks in the code:

namespace modules\site;

/**
 * site module definition class
 */
class Module extends \yii\base\Module
{
    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'modules\site\controllers\frontend';

    /**
     * @var boolean if we use admin module.
     */
    public $isBackend;

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // switch between frontend and backend
        if ($this->isBackend === true) {
            $this->controllerNamespace = 'modules\site\controllers\backend';
            $this->setViewPath('@modules/site/views/backend');
        } else {
            $this->setViewPath('@modules/site/views/frontend');
        }
    }
}

To set up access to Site module for the backend, you need to define it in the backend’s configuration file \backend\config\main.php as shown below:

...
  'modules' => [
        'site' => [
            'isBackend' => true,
        ]
    ],
…

Replace the following string:

'controllerNamespace' => 'backend\controllers',

With:

'defaultRoute' => 'site/site/index',

Now, you can create controllers in /modules/site/controllers/backend folder for the backend. Let’s move the controller SiteController.php from /backend/controllers folder to /modules/site/controllers/backend and replace namespace in it.

After we have refactored the existing controllers, models, and views and have moved them to our Site module, the module has changed a lot. Now it looks like the picture below:

3.jpg

Summing It Up

In this article, I’ve tried to summarize why we chose this or that technology to develop our large, demanding project. I’ve also offered several ways of how to develop a modular application using the Yii2 framework.

This is the first article in the series. In the following articles, I will share our team’s approach to developing demanding projects. Read on to learn how to solve multiple problems and issues that a developer faces when creating a modular app from scratch.

In the next article, we will talk about how to set up routing and create URLs using urlManager for each specific module. I will also explain how to create a set of rules for specific URLs by writing classes and routines that reinforce UrlRuleInterface.

Thanks for your time! If you have any questions, ask them in the comments section below or through contacts on the site clever-solution.com. Tune in for more!