- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
-
Special Topics
- Dependency Injection (DI) in Yii2
Dependency Injection (DI) in Yii2
Add to BookmarkIntroduction
Dependency Injection (DI) is a design pattern that promotes loose coupling by allowing dependencies to be injected rather than hardcoded within classes. Yii2 provides a built-in DI container to manage dependencies efficiently.
In this tutorial, we will explore how DI works in Yii2, its benefits, and two real-world examples:
- Using DI in a REST API (Payment Gateway System)
- Using DI in a Web Application (Notification System)
Understanding Dependency Injection in Yii2
Why Use Dependency Injection?
- Reduces tight coupling between classes
- Improves code maintainability and testability
- Makes it easier to switch implementations without modifying code
Yii2 Dependency Injection Container
Yii2 provides a built-in DI container accessible via Yii::$container
. This container allows you to define and resolve dependencies dynamically.
Example 1: Dependency Injection in a REST API (Payment Gateway System)
Step 1: Define an Interface
First, create an interface that all payment gateways must implement.
namespace app\services;
interface PaymentGatewayInterface {
public function charge($amount);
}
Step 2: Create Implementations
Stripe Payment Gateway
namespace app\services;
class StripePayment implements PaymentGatewayInterface {
public function charge($amount) {
return "Charged $amount via Stripe";
}
}
PayPal Payment Gateway
namespace app\services;
class PayPalPayment implements PaymentGatewayInterface {
public function charge($amount) {
return "Charged $amount via PayPal";
}
}
Step 3: Register Payment Gateway in DI Container
Modify config/web.php
to set a default payment gateway.
return [
'bootstrap' => [
function () {
Yii::$container->set(PaymentGatewayInterface::class, StripePayment::class);
}
],
];
Step 4: Inject Dependency into a Controller
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\services\PaymentGatewayInterface;
class PaymentController extends Controller {
private $paymentGateway;
public function __construct($id, $module, PaymentGatewayInterface $paymentGateway, $config = []) {
$this->paymentGateway = $paymentGateway;
parent::__construct($id, $module, $config);
}
public function actionCharge() {
$amount = Yii::$app->request->get('amount', 100);
return $this->paymentGateway->charge($amount);
}
}
Example 2: Dependency Injection in a Web Application (Notification System)
Step 1: Define an Interface
namespace app\services;
interface NotificationServiceInterface {
public function send($recipient, $message);
}
Step 2: Create Implementations
Email Notification Service
namespace app\services;
class EmailNotificationService implements NotificationServiceInterface {
public function send($recipient, $message) {
return "Email sent to {$recipient} with message: '{$message}'";
}
}
SMS Notification Service
namespace app\services;
class SmsNotificationService implements NotificationServiceInterface {
public function send($recipient, $message) {
return "SMS sent to {$recipient} with message: '{$message}'";
}
}
Step 3: Register Notification Service in DI Container
Modify config/web.php
to set a default notification service.
return [
'bootstrap' => [
function () {
Yii::$container->set(NotificationServiceInterface::class, EmailNotificationService::class);
}
],
];
Step 4: Using the Notification Service Without Explicit Injection
Since the service is registered in Yii::$container
, it can be retrieved anywhere in the application using Yii::$container->get()
.
Example: Calling Notification Service in a Controller Method
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\services\NotificationServiceInterface;
class NotificationController extends Controller {
public function actionSend() {
$recipient = Yii::$app->request->get('recipient', 'user@example.com');
$message = Yii::$app->request->get('message', 'Hello from Yii2!');
$notificationService = Yii::$container->get(NotificationServiceInterface::class);
$response = $notificationService->send($recipient, $message);
return $this->render('send', ['response' => $response]);
}
}
Example: Using Notification Service in a Model
namespace app\models;
use Yii;
use app\services\NotificationServiceInterface;
use yii\db\ActiveRecord;
class User extends ActiveRecord {
public function afterSave($insert, $changedAttributes) {
parent::afterSave($insert, $changedAttributes);
if ($insert) {
$notificationService = Yii::$container->get(NotificationServiceInterface::class);
$notificationService->send($this->email, "Welcome to our platform, {$this->name}!");
}
}
}
Example: Sending Notification Inside a Component
namespace app\components;
use Yii;
use app\services\NotificationServiceInterface;
class OrderProcessor {
public function processOrder($order) {
Yii::$container->get(NotificationServiceInterface::class)->send($order->user->email, "Your order #{$order->id} has been processed.");
}
}
Conclusion
Summary of Approaches
Approach | Pros | Cons |
---|---|---|
Injecting in Controller | - Makes dependencies explicit- Better for Unit Testing | - Requires passing dependency manually |
Fetching from DI Container | - Can be used anywhere in app- No need to inject into constructor | - Harder to mock for testing |
Using Dependency Injection in Yii2 allows for clean, maintainable, and testable code. Whether you choose to inject dependencies in controllers or resolve them directly from the DI container, Yii2 provides a flexible and efficient way to manage dependencies in your application.
Prepare for Interview
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
Random Blogs
- Mastering SQL in 2025: A Complete Roadmap for Beginners
- Top 10 Knowledge for Machine Learning & Data Science Students
- Top 15 Recommended SEO Tools
- Top 10 Blogs of Digital Marketing you Must Follow
- Deep Learning (DL): The Core of Modern AI
- Datasets for Natural Language Processing
- Robotics & AI – How AI is Powering Modern Robotics
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- The Ultimate Guide to Data Science: Everything You Need to Know
- Datasets for Speech Recognition Analysis
- Python Challenging Programming Exercises Part 3
- Grow your business with Facebook Marketing
- Store Data Into CSV File Using Python Tkinter GUI Library
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- How AI Companies Are Making Humans Fools and Exploiting Their Data
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset