- 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
Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
Modern web applications often require a separation between backend and frontend. Yii2, as a PHP framework, works excellently as a backend API, while frontend frameworks like Angular, Vue, and React handle the UI.
In this tutorial, we will explore:
- Setting up Yii2 as a REST API backend
- Configuring CORS to allow frontend access
- Integrating Yii2 with Angular, Vue, and React step by step
1. Setting Up Yii2 as a REST API Backend
Yii2 provides a powerful RESTful API structure through its built-in ActiveController.
1.1 Enable Yii2 API in config/web.php
Modify the components section:
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
]
This ensures Yii2 can handle JSON-based requests.
1.2 Create an API Controller
Yii2 provides ActiveController to expose models as API endpoints.
Create controllers/ApiController.php
:
namespace app\controllers;
use yii\rest\ActiveController;
use yii\filters\Cors;
class ApiController extends ActiveController
{
public $modelClass = 'app\models\User'; // Example model
public function behaviors()
{
$behaviors = parent::behaviors();
// Enable CORS for frontend requests
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
'Origin' => ['*'], // Change this to your frontend domain in production
'Access-Control-Allow-Methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
'Access-Control-Allow-Headers' => ['Authorization', 'Content-Type'],
],
];
return $behaviors;
}
}
Now, your Yii2 API is accessible at:
http://yourapp.com/api
- Supports CRUD operations on the
User
model - Allows requests from any frontend using CORS
2. Connecting Yii2 with Angular
2.1 Create an Angular Service to Fetch Data
Run the Angular project:
ng new my-angular-app
cd my-angular-app
ng generate service user
Modify src/app/user.service.ts
:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'http://yourapp.com/api';
constructor(private http: HttpClient) {}
getUsers(): Observable<any> {
return this.http.get(`${this.apiUrl}`);
}
}
2.2 Use the Service in a Component
Modify src/app/app.component.ts
:
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-root',
template: `<ul><li *ngFor="let user of users">{{ user.name }}</li></ul>`
})
export class AppComponent implements OnInit {
users: any[] = [];
constructor(private userService: UserService) {}
ngOnInit() {
this.userService.getUsers().subscribe(data => {
this.users = data;
});
}
}
Angular is now fetching real-time data from Yii2 API!
3. Connecting Yii2 with Vue.js
3.1 Install Vue & Axios
vue create my-vue-app
cd my-vue-app
npm install axios
3.2 Fetch Yii2 Data Using Axios
Modify src/components/UserList.vue
:
<template>
<div>
<h2>Users</h2>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
users: [],
};
},
mounted() {
axios.get("http://yourapp.com/api").then(response => {
this.users = response.data;
});
},
};
</script>
Vue is now rendering Yii2 API data dynamically!
4. Connecting Yii2 with React
4.1 Install React & Axios
npx create-react-app my-react-app
cd my-react-app
npm install axios
4.2 Fetch Yii2 Data in React Component
Modify src/App.js
:
import React, { useState, useEffect } from "react";
import axios from "axios";
function App() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios.get("http://yourapp.com/api").then(response => {
setUsers(response.data);
});
}, []);
return (
<div>
<h2>Users</h2>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default App;
React is now displaying live Yii2 API data!
5. Securing Yii2 API for Frontend Use
5.1 Restrict CORS to Specific Domains
Instead of allowing all origins ('*'
), modify ApiController.php
:
'cors' => [
'Origin' => ['https://my-angular-app.com', 'https://my-vue-app.com', 'https://my-react-app.com'],
],
This ensures only trusted frontend apps can access your Yii2 API.
5.2 Add Authentication to Yii2 API
Modify ApiController.php
:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => \yii\filters\auth\HttpBearerAuth::class,
];
return $behaviors;
}
This requires API requests to include an authentication token.
6. Deploy Yii2 & Frontend
6.1 Deploy Yii2 API to Hostinger
Follow our Yii2 Deployment Guide and use:
ln -s /home/user/projects/yii2-api /home/user/domains/mydomain.com/public_html/api
6.2 Deploy Angular/Vue/React to Hostinger
Build the project:
# For Angular
ng build --prod
# For Vue
npm run build
# For React
npm run build
Upload the dist
or build
folder to Hostinger’s public_html.
Configure .htaccess
to serve the frontend:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
Now, your Yii2 API + Frontend are live on Hostinger!
What We Achieved?
Yii2 is now fully integrated with Angular, Vue, and React.
- REST API in Yii2 – Serving JSON data
- Angular/Vue/React Integration – Fetching and displaying Yii2 data
- Security Best Practices – CORS & Authentication
- Deployment on Hostinger – With proper folder structure
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Exploratory Data Analysis On Iris Dataset
- Quantum AI – The Future of AI Powered by Quantum Computing
- The Ultimate Guide to Data Science: Everything You Need to Know
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Top 10 Blogs of Digital Marketing you Must Follow
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Loan Default Prediction Project Using Machine Learning
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- SQL Joins Explained: A Complete Guide with Examples
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- What Is SEO and Why Is It Important?
- Store Data Into CSV File Using Python Tkinter GUI Library
- 15 Amazing Keyword Research Tools You Should Explore
- Grow your business with Facebook Marketing
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
Datasets for Machine Learning
- 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
- Bitcoin Heist Ransomware Address Dataset