Yii2 follows a well-organized directory structure that adheres to the Model-View-Controller (MVC) design pattern. Whether you are using the Basic Template or the Advanced Template, understanding the directory structure is crucial for efficient development.
1. Yii2 Basic Template Directory Structure
The Basic Template is suitable for small to medium-sized applications and has the following structure:
controllers/ → Contains controller classes that handle user requests.
models/ → Stores model classes for interacting with the database.
runtime/ → Stores temporary files such as logs and cache.
tests/ → Contains automated test scripts.
vendor/ → Third-party dependencies managed by Composer.
views/ → Holds view files for rendering UI.
web/ → The entry point (index.php) and public assets (CSS, JS, images).
widgets/ → Contains reusable UI components.
yii → The Yii2 framework bootstrap file.
2. Yii2 Advanced Template Directory Structure
The Advanced Template is designed for enterprise applications and consists of separate frontend and backend sections, along with a shared directory for common code.
Yii2 is based on MVC architecture, which separates an application into three interconnected parts:
Model (models/) → Manages data and business logic.
View (views/) → Handles the presentation layer (UI).
Controller (controllers/) → Receives user requests, processes them, and returns responses.
For example, when a user visits site/index:
The controller (SiteController.php) processes the request.
The model (Post.php) fetches data from the database (if needed).
The view (views/site/index.php) renders the response.
4. Best Practices for Organizing Code
Follow Yii2’s directory structure to maintain code clarity.
Place reusable components in widgets/.
Keep business logic separate by using models/ instead of writing queries inside controllers.
Store configuration in config/ instead of hardcoding values.
This tutorial provides a comprehensive understanding of Yii2’s directory structure. In the next tutorial, we will explore Yii2's configuration files and environment settings to customize our application.