Home > PHP Framework > Laravel > How to use Laravel to implement separate deployment of front-end and back-end

How to use Laravel to implement separate deployment of front-end and back-end

PHPz
Release: 2023-04-23 09:56:14
Original
2272 people have browsed it

In today's Internet world, software services with Web applications as the core are becoming more and more popular. Among them, the Laravel framework, as an excellent development framework for PHP language, not only has efficient performance, but also has a series of advantages such as friendly development experience, rich open source community, powerful ORM and migration system. In Laravel's back-end development, the development model of front-end and back-end separation has gradually become popular recently. This article will introduce how to use Laravel to achieve separate deployment of front-end and back-end.

1. What is front-end and back-end separation

Front-end and front-end separation is a new way of developing web applications, which completely separates the front-end and back-end from a technical perspective. The front-end program is responsible for generating the interface and communicating with the server to obtain data, while the background program is responsible for processing business logic and accessing the database.

This approach has many benefits. First, it can improve the efficiency of front-end and back-end development. Front-end and back-end developers can develop in parallel, reducing dependence on each other; secondly, it can improve application performance. Since front-end and back-end services can be deployed and expanded separately, the overall performance of the system can be greatly improved. In addition, this approach allows both front-end and back-end developers to focus on their respective areas as much as possible, improving code quality and maintainability.

2. Implementation of front-end and back-end separation in Laravel

In Laravel development, the implementation of front-end and back-end separation requires the use of some front-end frameworks. Among them, we can use mainstream frameworks such as Vue.js, React or Angular as front-end development solutions. In Laravel, we can use the following two methods to achieve the separation of front-end and back-end.

  1. Create a new front-end project

We can create an independent front-end project first, and then interact with the Laravel backend through the API. In this mode, Laravel is only responsible for writing the back-end data API interface, and the front-end uses AJAX or Fetch API to request the back-end data interface. The front-end and back-end codes can be deployed on different servers or ports.

The advantage of this approach is that the separation between the front-end and the back-end is very high. Developers can give full play to their respective advantages while also improving the performance of the application. You can also use some modern front-end frameworks and tools to improve development efficiency and development experience.

The following is a simple example to demonstrate the implementation of this method. Let's take Laravel as the backend and Vue.js as the frontend as an example:

1.1 Create a new Laravel project

First, we need to create a new Laravel project in the command line:

composer create-project --prefer-dist laravel/laravel blog
Copy after login
Copy after login

1.2 Create a new Vue.js project

Next, we need to create a new Vue.js project:

npm install -g vue-cli
vue init webpack frontend
Copy after login

1.3 Configure Laravel and Vue.js

Next, we need to configure the routes/api.php file to respond to requests from the Vue.js front-end.

Route::get('/todos', function () {
    return App\Todo::all();
});
Copy after login

In frontend/src/App.vue we can use Axios or any other AJAX library to get the backend API. In this example we will use the Axios library.

<template>
  <div class="todo-list">
    <div class="todo" v-for="todo in todos" :key="todo.id">
      <input type="checkbox" :checked="todo.completed" @change="toggle(todo)">
      <label>{{ todo.title }}</label>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      todos: []
    }
  },
  created () {
    axios.get('/api/todos')
      .then(response => {
        this.todos = response.data
      })
      .catch(error => {
        console.log(error)
      })
  },
  methods: {
    toggle (todo) {
      todo.completed = !todo.completed
      axios.put('/api/todos/' + todo.id, todo)
        .then(response => {})
        .catch(error => {
          console.log(error)
        })
    }
  }
}
</script>
Copy after login

In frontend/config/index.js we can set the Vue.js frontend to use a different port than the Laravel backend. We can then run and access the application.

php artisan serve --port=8000
cd frontend
npm start
Copy after login
  1. Use Laravel Mix to package front-end projects

Another way is to package the front-end code and Laravel back-end code into the same project for deployment. In this mode, Laravel Mix is ​​used as a tool for building front-end applications. Laravel Mix is ​​a simplified Webpack build tool that allows us to easily package front-end resources.

The advantage of this method is that the front-end and back-end codes will be packaged into a whole, which is convenient for deployment and maintenance. We can use commands similar to npm run dev and npm run build to compile the front-end code and place the compilation results in Laravel's public directory so that we can view them through the browser Access the application directly.

The following is a simple example to demonstrate the implementation of this method:

2.1 Create a new Laravel project

First, we need to create a new Laravel project in the command line Laravel Project:

composer create-project --prefer-dist laravel/laravel blog
Copy after login
Copy after login

2.2 Install Node.js and NPM

In the next steps, we need to install Node.js and NPM.

In Ubuntu, you can use the following command to install:

sudo apt-get install nodejs
sudo apt-get install npm
Copy after login

2.3 Install Laravel Mix in Laravel

Then, we need to install Laravel Mix:

npm install --save-dev laravel-mix
Copy after login

Then, we need to execute the following command to generate the webpack.mix.js configuration file:

node_modules/.bin/mix
Copy after login

2.4 Write the front-end code

Next, we need to write the front-end code. For example, we can write some JavaScript code in the resources/assets/js/app.js file. The following is a simple example:

"use strict";

window.Vue = require('vue');

Vue.component('example-component', require('./components/ExampleComponent.vue'));

const app = new Vue({
    el: '#app'
});
Copy after login

2.5 Writing front-end resources

We can put the front-end resource files in the resources/assets directory. For example, we can write some CSS styles in resources/assets/sass/app.scss.

html, body {
  height: 100%;
  margin: 0;
}

#app {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.title {
  font-size: 24px;
  text-align: center;
}
Copy after login

2.6 Configuring Laravel Mix

我们需要在 webpack.mix.js 文件中配置 Laravel Mix。例如,我们可以使用 .sass() 方法来生成 CSS 文件,并使用 .js() 方法来生成 JavaScript 文件:

const mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');
Copy after login

2.7 编译前端资源

接下来,我们可以运行以下命令来编译前端资源:

npm run dev
Copy after login

npm run watch
Copy after login

这样,我们就可以在浏览器中看到我们的应用程序了。

  1. 部署应用程序

无论我们使用哪种方式来实现前后端分离,最终都需要进行部署。我们可以使用第三方工具如 Jenkins、Capistrano 和 Docker Compose 等来自动化部署。这里介绍一种基于 NGINX + PHP-FPM + MySQL 的部署方式。

3.1 安装服务

首先,我们需要安装 NGINX、PHP-FPM 和 MySQL。我们可以使用以下命令在 Ubuntu 中进行安装:

sudo apt-get install nginx
sudo apt-get install mysql-server
sudo apt-get install php-fpm
Copy after login

3.2 配置 NGINX

接下来,我们需要配置 NGINX。我们可以在 /etc/nginx/sites-available 目录下创建一个新的配置文件。以下是配置文件的示例:

server {
    listen 80;
    server_name yourdomain.com;

    root /var/www/public;

    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ /\. {
        deny all;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        internal;
    }
}
Copy after login

我们需要将我们的代码放置在 /var/www/public 目录中。例如,我们使用前两种方式中的第一种方式,代码存放在了一个 独立的前端项目 中。我们可以使用以下命令将编译好的前端代码复制到 /var/www/public 目录中:

cp -r /path/to/frontend/dist/* /var/www/public
Copy after login

3.3 配置 MySQL

接下来,我们需要配置 MySQL。我们可以使用以下命令进行安全设置:

sudo mysql_secure_installation
Copy after login

然后,我们可以创建一个新的 MySQL 数据库:

CREATE DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'dbuser'@'localhost' IDENTIFIED BY 'dbpassword';
GRANT ALL PRIVILEGES ON dbname.* TO 'dbuser'@'localhost';
Copy after login

在 Laravel 的 .env 配置文件中,我们需要进行如下数据库配置:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpassword
Copy after login

3.4 执行数据库迁移

接下来,我们需要执行 Laravel 数据库迁移,并进行一些初始化操作:

php artisan migrate
php artisan db:seed
php artisan key:generate
Copy after login

3.5 重启服务

最后,我们需要重启 NGINX 和 PHP-FPM 服务,使配置生效:

sudo systemctl restart nginx
sudo systemctl restart php7.4-fpm
Copy after login

至此,我们可以通过浏览器访问我们的应用程序,Laravel 前后端分离部署就完成了。

三、结论

本文介绍了使用 Laravel 实现前后端分离部署的两种方式:创建一个新的前端项目和使用 Laravel Mix 打包前端项目两种方式。当然,对于前端开发人员来说,也可以选择自己熟悉的框架、编程语言来进行前端开发,只需要遵循前后端分离的原则即可。总之,Laravel 的灵活性使得它可以与许多现代前端框架和工具配合使用,让开发人员可以更自由地选择适合自己的开发方式。

The above is the detailed content of How to use Laravel to implement separate deployment of front-end and back-end. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template