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:
Yii2 provides a powerful RESTful API structure through its built-in ActiveController.
config/web.phpModify the components section:
'components' => [
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
]This ensures Yii2 can handle JSON-based requests.
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/apiUser modelRun the Angular project:
ng new my-angular-app
cd my-angular-app
ng generate service userModify 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}`);
}
}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!
vue create my-vue-app
cd my-vue-app
npm install axiosModify 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!
npx create-react-app my-react-app
cd my-react-app
npm install axiosModify 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!
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.
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.
Follow our Yii2 Deployment Guide and use:
ln -s /home/user/projects/yii2-api /home/user/domains/mydomain.com/public_html/apiBuild the project:
# For Angular
ng build --prod
# For Vue
npm run build
# For React
npm run buildUpload 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!
Yii2 is now fully integrated with Angular, Vue, and React.
Sign in to join the discussion and post comments.
Sign in