PHPackages                             mgrechanik/yii2-universal-module-sceleton - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mgrechanik/yii2-universal-module-sceleton

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

mgrechanik/yii2-universal-module-sceleton
=========================================

The structure of universal Yii2 module who fits both to advanced and basic templates

1.0.2(6y ago)310.9k↓45.6%1BSD-3-ClausePHP

Since Dec 9Pushed 6y ago2 watchersCompare

[ Source](https://github.com/mgrechanik/yii2-universal-module-sceleton)[ Packagist](https://packagist.org/packages/mgrechanik/yii2-universal-module-sceleton)[ RSS](/packages/mgrechanik-yii2-universal-module-sceleton/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (2)Versions (4)Used By (1)

Yii2 universal module sceleton
==============================

[](#yii2-universal-module-sceleton)

[Русская версия](docs/README_ru.md)

Table of contents
-----------------

[](#table-of-contents)

- [Goal](#goal)
- [Installing](#installing)
- [What it is about](#gist)
- [Using](#using)
- [Module inheritance](#inheritance)
- [Module settings](#settings)
- [Example with *Basic* template](#example-basic)
- [How-to](#recipe)

---

Goal
-----

[](#goal-)

This extension gives the structure of the module which:

1. will be self-sufficient and portable because it holds all his functionality in one place
2. logically divided at **backend** and **frontend** parts
3. easily connects both to *Advanced* and *Basic* application templates
4. with *Basic* application template:

    - connects to module section only one time
    - there is functionality of protection to all **backend** controllers (for admin part of your web site)
5. it is easy to inherit such modules from one another to override functionality without controllers duplication

---

Installing
-----------

[](#installing-)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).:

Either run

```
composer require --prefer-dist mgrechanik/yii2-universal-module-sceleton

```

or add

```
"mgrechanik/yii2-universal-module-sceleton" : "~1.0.0"

```

to the require section of your `composer.json`

---

What it is about
-----------------

[](#what-it-is-about--)

- By default module controllers are being searched automatically in it's `$controllerNamespace`
- We do not use this functionality but define all our controllers in module's `$controllerMap`
- But we do this not by `$controllerMap` property explicitly but define **backend** and **frontend** controllers separately
- Module has **the mode**  which is set in config; according to this mode `Controller Map`will have **only** those controllers who fit the mode:
    - With **frontend** application of *Advanced* template we connect our module in `'frontend'` mode
    - With **backend** application of *Advanced* template we connect our module in `'backend'` mode
    - With *Basic* template we can connect our module in two modes described above and also in `'backend and frontend'` mode when both controller types are accessible
- When module get the request it creates the controller from their map, figuring by it's namespace
    whether it is **backend** or **frontend** controller to perform additional set up
- Module expects the next directory structure:

```
Module_directory/
   ui/                                  // User Interface of the module
      controllers/
          backend/                      // Backend controllers like the next:
            AdminDefaultController.php
            ...
          frontend/                     // Frontend controllers like the next:
            DefaultController.php
            ...
      views/                            // Views for corresponding controllers
          backend/
            admin-default/
          frontend/
            default/
   Module.php                           // module class

```

---

Using
------

[](#using--)

1. Generate, or create manually, your module class
2. Inherit your module class from universal module class

```
use mgrechanik\yiiuniversalmodule\UniversalModule;

class YourModule extends UniversalModule
{
```

3. Now create (or generate) **frontend** controller

- Take into consideration that it's `namespace` should be `yourModuleNamespace\ui\controllers\frontend`
- Create all subdirs needed
- According to controller it's views will reside in `@yourModuleNamespace/ui/views/frontend/YourControllerName/`
- We need to define this controller in **frontend** controller map of this module:

```
class YourModule extends UniversalModule
{
    public $frontendControllers = [
        'default',
    ];
```

, where `'default'` match `yourModuleNamespace\ui\controllers\frontend\DefaultController`.
When the name and class of controller do not match use next definition form: `'default2' => 'SomeDefaultController'`.

> **Always when you create new controller do not forget to define it in appropriate controller map of your module.**

You are not required to inherit your controller classes from any parent type.

4. Now create (or generate) **backend** controller

- Logic is the same with 3), but it's `namespace` should be `yourModuleNamespace\ui\controllers\backend`
- Define it in module at:

```
class YourModule extends UniversalModule
{
    public $backendControllers = [
        'admin-default',
    ];
```

- It is handy to prefix **backend** controller names with **Admin**, so all backend urls could be [set up](#recipe-admin-url) the way all of them will start with **admin/**

5. Done, your module is ready, you can **connect it to application**:

**config/main.php:**

```
    // ...
    'modules' => [
        'yourModule' => [
            'class' => 'yourModuleNamespace\YourModule',
            'mode' => 'frontend',
        ],
```

, do not forget to define - [mode](#mode)

> It is comfortable to connect all such modules at first level of application modules, without nested modules but like a simple list of modules we used to see at admin pages of popular **CMS**s, which also gives short urls.

---

Module inheritance
-------------------

[](#module-inheritance-)

When you inherit your module class from existing one without overriding `$frontendControllers`and `$backendControllers` the next happens:

1. These two properties will be taken from parent naturally
2. But the basic controller namespace will be set to your module namespace. You do not have such controllers and you do not want to create their copies
3. There are next opportunities how to make your module to use controllers from any of his ancestors:
    - If controllers reside with **immediate** parent of your module set it the next property `$takeControllersFromParentModule = true`
    - If controllers are in some other module, say `'Omega'`, then set the property of your module `$baseControllerNamespace` to **namespace** of `'Omega'` module
    - `Views` will be searched by default according to settings above

---

Module settings
----------------

[](#module-settings-)

[Connecting](#setup) module to application we can use next it's properties:

#### `$mode` - mode in which this module works

[](#mode---mode-in-which-this-module-works)

You are required to set up it. [Details](#mode)

#### `$backendLayout` - layout for backend controllers

[](#backendlayout---layout-for-backend-controllers)

Sets up `layout` to module when **backend** controller is requested.
It is useful for *Basic* application template.

#### `$frontendControllers` - frontend controller map

[](#frontendcontrollers---frontend-controller-map)

[Details](#fcontroller)

#### `$backendControllers` - backend controller map

[](#backendcontrollers---backend-controller-map)

[Details](#bcontroller)

#### `$controllerMapAdjustCallback` - callback for final adjustment of controller map

[](#controllermapadjustcallback---callback-for-final-adjustment-of-controller-map)

After module's controller map is generated you can adjust it with this function which signature is: `function($map) { ...; return $map; }`

#### `$backendControllerConfig` - **backend** controllers settings

[](#backendcontrollerconfig---backend-controllers-settings)

When module [creates](#mknows) **backend** controller it could set up controller with these properties.

It is handy, for example, to restrict access to such controllers using yii filters connected like behaviors.

[Example of using](#example-basic).

#### `$frontendControllerConfig` - **frontend** controllers settings

[](#frontendcontrollerconfig---frontend-controllers-settings)

It is the same like `$backendControllerConfig`

#### `$baseControllerNamespace` - the basic namespace for the controllers the module uses

[](#basecontrollernamespace---the-basic-namespace-for-the-controllers-the-module-uses)

By default it is not used and controllers will be searched relevant to your current module namespace.
But with this property you can tell to take controllers from any other module

#### `$takeControllersFromParentModule` - whether to take controllers from parent

[](#takecontrollersfromparentmodule---whether-to-take-controllers-from-parent)

It is `false` by default, meaning no taking.
But with this property you can tell to take controllers from immediate parent of current module

#### `$baseViewsPath` - basic path where to find module's `views`

[](#baseviewspath---basic-path-where-to-find-modules-views)

By default it is not used.
It is automatically set up whether to current module directory or relevant to the two properties above when they are set.
But with this property you can finally say where to search for `views`. Example of value: `'@mgrechanik/yii2catalog'`

---

Example of module's set up with *Basic* application template
-------------------------------------------------------------

[](#example-of-modules-set-up-with-basic-application-template-)

Lets suppose that we have two modules we are talking about - `example` and `omega`.
Here is working configs to set up these modules:

**config/params.php:**

```
return [
    'backendLayout' => '//lte/main',
    'backendControllerConfig' => [
        'as backendaccess' => [
            'class' => \yii\filters\AccessControl::class,
            'rules' => [
                [
                    'allow' => true,
                    'ips' => ['54.54.22.44'],
                    'matchCallback' => function ($rule, $action){
                        $user = \Yii::$app->user;
                        return !$user->isGuest &&
                            ($user->id == 1);
                },
                ]
            ],
        ],
    ],

];
```

At this config we gave permission to "admin pages" only to one user `(id==1)`, with additional check for `ip`.

**config/web.php:**

```
    'components' => [
	//...
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                'admin/-/' =>
                    '/admin-/',
                'admin/-' =>
                    '/admin-',
            ],
        ],
    ],
    'modules' => [
        'example' => [
            'class' => 'modules\example\Module',
            'mode' => 'backend and frontend',
            'backendLayout' => $params['backendLayout'],
            'backendControllerConfig' => $params['backendControllerConfig'],
        ],
        'omega' => [
            'class' => 'modules\username1\omega\Module',
            'mode' => 'backend and frontend',
            'backendLayout' => $params['backendLayout'],
            'backendControllerConfig' => $params['backendControllerConfig'],
        ],
    ],
```

---

How-to
-------

[](#how-to-)

#### Make all admin urls start with `/admin`

[](#make-all-admin-urls-start-with-admin--)

Lets see *Basic* application template with two "our" modules connected to it:

```
    'modules' => [
        'example' => [
            ...
        ],
        'omega' => [
            ...
        ],
```

If we followed [advice](#bcontroller) above about naming of **backend** controllers all of them have names like `Admin...Controller`.
So urls to them will be `example/admin-default` and `omega/admin-default`.
And we want all our admin urls to start with `admin/`.

It is easily achived with the next two `Url Rules` for your `urlManager`:

```
	'urlManager' => [
		'enablePrettyUrl' => true,
		'showScriptName' => false,
		'rules' => [
			'admin/-/' =>
				'/admin-/',
			'admin/-' =>
				'/admin-',
		],
	],
```

#### Generating **backend** functionality with Gii CRUD generator

[](#generating-backend-functionality-with-gii-crud-generator---)

You can easily generate CRUD functionality considering that:

- The `name` and the `namespace` of the **controller** should be choosen according to [documentation](#bcontroller)
- `View Path` should match [directory structure](#dir-structure) the module demands

#### How to connect the module to console application?

[](#how-to-connect-the-module-to-console-application---)

If our module has console commands who reside for example here:

```
Module_directory/
  console/
    commands/                // Directory for console commands
      HelloController.php
  Module.php

```

, then in the console application config this module is connected like:

```
    'modules' => [
        'example' => [
            'class' => 'modules\example\Module',
            'controllerNamespace' => 'yourModuleNamespace\console\commands',
        ],
    ],
```

#### Where to put all other module's functionality?

[](#where-to-put-all-other-modules-functionality---)

This module regulates only [directory structure](#dir-structure) described above where only from **controllers** and **views** their concrete positions are expected.
When writing the rest of functionality you may follow the next advices:

- If a component is definitely related only to one part of application - **backend** or **frontend**then put it in the corresponding subdirectory
- If there is no such definite separation put it in the root of his directory

For example for models:

```
  models/
    backend/
      SomeBackendModel.php
    frontend/
      SomeFrontendModel.php
    SomeCommonModel.php

```

- Since for all user interface of our module we have already created `ui/` subdirectory then put **forms** and **widgets** there

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~22 days

Total

3

Last Release

2347d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/83919f51df37e9d419895f01a9d4f55ef44c0dc764aec2a57081b6c5e2a3ed8a?d=identicon)[mgrechanik](/maintainers/mgrechanik)

---

Top Contributors

[![mgrechanik](https://avatars.githubusercontent.com/u/5772506?v=4)](https://github.com/mgrechanik "mgrechanik (6 commits)")

---

Tags

skeletonskeleton-applicationyii2modulestructureadvancedbasicyii 2universal modulesceleton

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mgrechanik-yii2-universal-module-sceleton/health.svg)

```
[![Health](https://phpackages.com/badges/mgrechanik-yii2-universal-module-sceleton/health.svg)](https://phpackages.com/packages/mgrechanik-yii2-universal-module-sceleton)
```

###  Alternatives

[softark/yii2-dual-listbox

Bootstrap Dual Listbox Widget for Yii 2

20149.1k11](/packages/softark-yii2-dual-listbox)[vova07/yii2-start-comments-module

The comments module for Yii2-Start application.

149.5k1](/packages/vova07-yii2-start-comments-module)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
