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