Yii2.0—Module

Nov 25, 2016 pm 02:09 PM
yii module

A module is an independent software unit, consisting of models, views, controllers and other supporting components. End users can access the controllers of installed modules in the application body. The module is treated as a small application body, which is different from the application body. The important thing is that modules cannot be deployed individually and must belong to an application subject.

Create module

The module is organized into a directory called [[yiibaseModule::basePath|base path]]. In this directory, there are subdirectories such as controllers, models, and views for corresponding controllers, models, views, and The rest of the code is very similar to the application. The following example shows the directory structure of a model:

forum/
    Module.php                   模块类文件
    controllers/                 包含控制器类文件
        DefaultController.php    default 控制器类文件
    models/                      包含模型类文件
    views/                       包含控制器视图文件和布局文件
        layouts/                 包含布局文件
        default/                 包含DefaultController控制器视图文件
            index.php            index视图文件
Copy after login

Module class

Each module has a module class that inherits [[yiibaseModule]], and this class file is placed directly in the module's [[yiibaseModule::basePath|base path] ] directory and can be loaded automatically. When a module is accessed, a unique instance of the module class is created similar to the application body instance. The module instance is used to help the code within the module share data and components.

The following example roughly defines a module class:

namespace app\modules\forum; class Module extends \yii\base\Module { public function init() { parent::init(); $this->params['foo'] = 'bar'; 
// ...  其他初始化代码 ... } }
Copy after login

If the init() method contains a lot of code to initialize module properties, they can be saved in the configuration and loaded using the following code in init():

public function init() { parent::init(); // 从config.php加载配置来初始化模块 \Yii::configure($this, require(__DIR__ . '/config.php')); }
Copy after login

config.php configuration file It may contain the following content, similar to the application main configuration.

<?php return [ &#39;components&#39; => [ // list of component configurations ], &#39;params&#39; => [ // list of parameters ], ];
Copy after login

Controllers in modules

When creating a module's controller, the convention is to place the controller class in the controllers sub-namespace of the module class namespace, which also means Place the controller class files in the controllers subdirectory in the module [[yiibaseModule::basePath|base path]] directory. For example, to create a post controller in the forum module in the previous section, you should declare the controller class as follows:

namespace app\modules\forum\controllers; use yii\web\Controller; class PostController extends Controller { // ... }
Copy after login

You can configure the [[yiibaseModule::controllerNamespace]] attribute to customize the namespace of the controller class. If some controllers No longer in this namespace, you can configure the [[yiibaseModule::controllerMap]] attribute to make them accessible, similar to what is done in the application body configuration.

Views in the module

The views should be placed in the views directory under the directory corresponding to [[yiibaseModule::basePath|base path]] of the module. The view files corresponding to the controllers in the module should be placed under the views/ControllerID directory. Where ControllerID corresponds to the controller ID. For example, if For example, assuming that the controller class is PostController, the directory corresponds to the views/post directory under the module [[yiibaseModule::basePath|base path]] directory.

Modules can specify layout, which is used in the module's controller view rendering. The layout file is placed in the views/layouts directory by default. You can configure the [[yiibaseModule::layout]] attribute to specify the layout name. If the layout attribute name is not configured, the application layout will be used by default.

Using modules

To use modules in an application, you only need to add the module to the list of [[yiibaseApplication::modules|modules]] attributes of the application body configuration. The application body configuration of the following code uses the forum module:

[ &#39;modules&#39; => [ &#39;forum&#39; => [ &#39;class&#39; => &#39;app\modules\forum\Module&#39;, // ... 模块其他配置 ... ], ], ]
Copy after login
The

[[yiibaseApplication::modules|modules]] attribute uses a module configuration array. Each array key is the module ID, which identifies the unique module in the application. The value of the array is the configuration used to create the module.

Routing

Similar to accessing application controllers, routing is also used to address the controller in the module. The route for the controller in the module must start with the module ID, followed by the controller ID and operation ID. For example, assuming that the application uses a module named forum, the route forum/post/index represents the index operation of the post controller in the module. If the route only contains the module ID, the default [[yiibaseModule::defaultRoute]] attribute is used to determine the use. Which controller/action, that is, the routing forum may represent the default controller of the forum module.

Access module

In a module, you may often need to obtain an instance of a module class to access module ID, module parameters, module components, etc. You can use the following statement to obtain it:

$module = MyModuleClass::getInstance();
Copy after login

where MyModuleClass corresponds to the module class you want, The getInstance() method returns the currently requested module class instance. If the module is not requested, this method will return null. Note that there is no need to manually create a module class, because the manually created one is different from the one automatically created when Yii processes the request.

Supplement: When developing a module, you cannot assume that the module uses a fixed ID, because in the application or other modules, the module may correspond to any ID. In order to obtain the module ID, you should use the above code to obtain the module instance, and then Get the module ID through $module->id.

You can also access module instances using the following methods:

// 获取ID为 "forum" 的模块 $module = \Yii::$app->getModule('forum'); // 获取处理当前请求控制器所属的模块 $module = \Yii::$app->controller->module;

第一种方式仅在你知道模块ID的情况下有效,第二种方式在你知道处理请求的控制器下使用。

一旦获取到模块实例,可访问注册到模块的参数和组件,例如:

$maxPostCount = $module->params[&#39;maxPostCount&#39;];
Copy after login

引导启动模块

有些模块在每个请求下都有运行, [[yii\debug\Module|debug]] 模块就是这种, 为此将这种模块加入到应用主体的 [[yii\base\Application::bootstrap|bootstrap]] 属性中。

例如,如下示例的应用主体配置会确保debug模块每次都被加载:

[ &#39;bootstrap&#39; => [ &#39;debug&#39;, ], &#39;modules&#39; => [ &#39;debug&#39; => &#39;yii\debug\Module&#39;, ], ]
Copy after login

模块嵌套

模块可无限级嵌套,也就是说,模块可以包含另一个包含模块的模块,我们称前者为父模块,后者为子模块, 子模块必须在父模块的[[yii\base\Module::modules|modules]]属性中申明,例如:

namespace app\modules\forum; class Module extends \yii\base\Module { public function init() { parent::init(); $this->modules = [ &#39;admin&#39; => [ 
// 此处应考虑使用一个更短的命名空间 &#39;class&#39; => &#39;app\modules\forum\modules\admin\Module&#39;, ], ]; } }
Copy after login

在嵌套模块中的控制器,它的路由应包含它所有祖先模块的ID,例如forum/admin/dashboard/index代表 在模块forum中子模块admin中dashboard控制器的index操作。

最佳实践

模块在大型项目中常备使用,这些项目的特性可分组,每个组包含一些强相关的特性, 每个特性组可以做成一个模块由特定的开发人员和开发组来开发和维护。

在特性组上,使用模块也是重用代码的好方式,一些常用特性,如用户管理,评论管理,可以开发成模块, 这样在相关项目中非常容易被重用。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
WLAN expansion module has stopped [fix] WLAN expansion module has stopped [fix] Feb 19, 2024 pm 02:18 PM

If there is a problem with the WLAN expansion module on your Windows computer, it may cause you to be disconnected from the Internet. This situation is often frustrating, but fortunately, this article provides some simple suggestions that can help you solve this problem and get your wireless connection working properly again. Fix WLAN Extensibility Module Has Stopped If the WLAN Extensibility Module has stopped working on your Windows computer, follow these suggestions to fix it: Run the Network and Internet Troubleshooter to disable and re-enable wireless network connections Restart the WLAN Autoconfiguration Service Modify Power Options Modify Advanced Power Settings Reinstall Network Adapter Driver Run Some Network Commands Now, let’s look at it in detail

WLAN extensibility module cannot start WLAN extensibility module cannot start Feb 19, 2024 pm 05:09 PM

This article details methods to resolve event ID10000, which indicates that the Wireless LAN expansion module cannot start. This error may appear in the event log of Windows 11/10 PC. The WLAN extensibility module is a component of Windows that allows independent hardware vendors (IHVs) and independent software vendors (ISVs) to provide users with customized wireless network features and functionality. It extends the capabilities of native Windows network components by adding Windows default functionality. The WLAN extensibility module is started as part of initialization when the operating system loads network components. If the Wireless LAN Expansion Module encounters a problem and cannot start, you may see an error message in the event viewer log.

Python commonly used standard libraries and third-party libraries 2-sys module Python commonly used standard libraries and third-party libraries 2-sys module Apr 10, 2023 pm 02:56 PM

1. Introduction to the sys module The os module introduced earlier is mainly for the operating system, while the sys module in this article is mainly for the Python interpreter. The sys module is a module that comes with Python. It is an interface for interacting with the Python interpreter. The sys module provides many functions and variables to deal with different parts of the Python runtime environment. 2. Commonly used methods of the sys module. You can check which methods are included in the sys module through the dir() method: import sys print(dir(sys))1.sys.argv-Get the command line parameters sys.argv is used to implement the command from outside the program. The program is passed parameters and it is able to obtain the command line parameter column

How does Python's import work? How does Python's import work? May 15, 2023 pm 08:13 PM

Hello, my name is somenzz, you can call me Brother Zheng. Python's import is very intuitive, but even so, sometimes you will find that even though the package is there, we will still encounter ModuleNotFoundError. Obviously the relative path is very correct, but the error ImportError:attemptedrelativeimportwithnoknownparentpackage imports a module in the same directory and a different one. The modules of the directory are completely different. This article helps you easily handle the import by analyzing some problems often encountered when using import. Based on this, you can easily create attributes.

Python programming: Detailed explanation of the key points of using named tuples Python programming: Detailed explanation of the key points of using named tuples Apr 11, 2023 pm 09:22 PM

Preface This article continues to introduce the Python collection module. This time it mainly introduces the named tuples in it, that is, the use of namedtuple. Without further ado, let’s get started – remember to like, follow and forward~ ^_^Creating named tuples The named tuple class namedTuples in the Python collection gives meaning to each position in the tuple and enhances the readability of the code Sexual and descriptive. They can be used anywhere regular tuples are used, and add the ability to access fields by name rather than positional index. It comes from the Python built-in module collections. The general syntax used is: import collections XxNamedT

Detailed explanation of how Ansible works Detailed explanation of how Ansible works Feb 18, 2024 pm 05:40 PM

The working principle of Ansible can be understood from the above figure: the management end supports three methods of local, ssh, and zeromq to connect to the managed end. The default is to use the ssh-based connection. This part corresponds to the connection module in the above architecture diagram; you can press the application type HostInventory (host list) classification is carried out in other ways. The management node implements corresponding operations through various modules. A single module and batch execution of a single command can be called ad-hoc; the management node can implement a collection of multiple tasks through playbooks. Implement a type of functions, such as installation and deployment of web services, batch backup of database servers, etc. We can simply understand playbooks as, the system passes

How to use DateTime in Python How to use DateTime in Python Apr 19, 2023 pm 11:55 PM

All data are automatically assigned a "DOB" (Date of Birth) at the beginning. Therefore, it is inevitable to encounter date and time data when processing data at some point. This tutorial will take you through the datetime module in Python and using some peripheral libraries such as pandas and pytz. In Python, anything related to date and time is handled by the datetime module, which further divides the module into 5 different classes. Classes are simply data types that correspond to objects. The following figure summarizes the 5 datetime classes in Python along with commonly used attributes and examples. 3 useful snippets 1. Convert string to datetime format, maybe using datet

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

See all articles