」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 PHP 作為後端 使用 React 作為前端

如何使用 PHP 作為後端 使用 React 作為前端

發佈於2024-08-05
瀏覽:919

Introduction

Developing dynamic and interactive web apps is crucial in the dynamic and ever-changing world of web development. The speed and versatility of React, a JavaScript toolkit for creating user interfaces, have led to its great popularity. However, PHP is still a strong option for server-side programming. This tutorial will show you how to easily combine the functionality of a PHP backend and React front-end to utilize their respective strengths fully.

Understanding the Distinct Roles of PHP and React

What Is PHP

The term PHP is an acronym for Hypertext Preprocessor. It is a server-side scripting language that is used for web development. It can be easily embedded with HTML files. HTML codes can also be written in a PHP file.

Merits Of PHP

Below are a few Merits of PHP
Ease of Learning and Use:

  • PHP is known for its straightforward syntax, which is relatively easy for beginners. This simplicity helps new developers start building web applications quickly.

Wide Adoption and Community Support:

  • PHP has a large and active community. This means extensive documentation, numerous tutorials, and a wealth of online resources. Community support also translates into a vast pre-written code, frameworks, and plugin library.

Integration Capabilities:

  • PHP integrates seamlessly with various databases (such as MySQL, PostgreSQL, SQLite), web servers (like Apache and Nginx), and other services. This makes it a versatile choice for web development.

Open Source:

  • PHP is free to use and distribute. This lowers the cost of development, especially for small businesses and startups.

Cross-Platform Compatibility:

  • PHP can run on multiple platforms, including Windows, Linux, and macOS. This flexibility ensures that PHP applications can be deployed in diverse environments without compatibility issues.

Demerits Of PHP

Below are a few Demerits of PHP.

  1. Inconsistent Function Naming and Parameter Order:

    • One of the common criticisms of PHP is its inconsistent function naming conventions and parameter order. For example, functions may have different naming patterns (str_replace vs. strpos) and parameter orders (array_filter($array, $callback) vs. array_map($callback, $array)). This inconsistency can lead to confusion and errors, especially for new developers.
  2. Historical Security Issues:

    • PHP has had a history of security vulnerabilities, partly due to its widespread use and partly due to the way it was designed. While modern PHP has significantly improved in terms of security features, legacy codebases and bad practices from earlier versions can still pose security risks.
  3. Performance Compared to Other Languages:

    • While PHP has made great strides in improving performance (especially with PHP 7 and later), it can still be slower compared to some other languages like Node.js or Go for certain tasks. This can be a drawback for applications requiring extremely high performance and low latency.
  4. Weak Typing:

    • PHP’s weak typing system, which allows implicit type conversions, can lead to unexpected behavior and bugs that are difficult to track down. For example, comparing a string to a number may yield unexpected results ("123" == 123 is true, but "123" === 123 is false). This can be problematic, especially for large, complex codebases.
  5. Over-Reliance on Older, Procedural Code:

    • Many PHP applications and tutorials still use older, procedural programming techniques rather than modern, object-oriented, or functional programming practices. This can lead to less maintainable and harder-to-read code. While modern frameworks encourage better practices, the legacy of procedural code can still be a significant issue.

What Is React

React JS is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library, responsible only for the view layer of the application. It is maintained by Facebook.

Merits Of React Js

Below are a few Merits of React Js.

  1. Component-Based Architecture:

    • React follows a component-based architecture, which allows developers to build reusable UI components. This modularity leads to cleaner, more maintainable, and scalable code. Components can be reused across different parts of an application, reducing redundancy and improving development efficiency.
  2. Virtual DOM for Improved Performance:

    • React uses a Virtual DOM (Document Object Model) to optimize rendering performance. When the state of an application changes, React updates the Virtual DOM first, which then efficiently updates the actual DOM only where necessary. This minimizes direct manipulation of the DOM, leading to faster and more efficient updates, particularly beneficial for complex applications with frequent UI changes.
  3. Declarative UI:

    • React's declarative approach to building UIs makes code more predictable and easier to debug. Developers describe what the UI should look like for a given state, and React takes care of updating the actual UI based on state changes. This simplifies the process of developing interactive user interfaces and makes the code more readable.
  4. Rich Ecosystem and Community Support:

    • React has a vast ecosystem with numerous libraries, tools, and extensions that enhance its functionality. The strong community support ensures that developers have access to extensive resources, tutorials, and third-party components. Additionally, the backing of Facebook and contributions from a large number of developers worldwide ensure React remains up-to-date and continuously improving.
  5. Strong Support for JSX:

    • React uses JSX (JavaScript XML), a syntax extension that allows HTML to be written within JavaScript. JSX simplifies the process of creating React components and makes the code more readable by visually separating the structure (HTML) from the logic (JavaScript). This tight integration of markup with logic enhances development efficiency and reduces context switching for developers.

Demerits Of React Js

Below are a few Demerits of React Js.

  1. Steep Learning Curve:

    • React's flexibility and the wide array of tools and libraries in its ecosystem can make the learning curve steep for beginners. Understanding concepts like JSX, components, state management, and the intricacies of the Virtual DOM can be challenging for new developers.
  2. Boilerplate and Complexity:

    • Setting up a React project often involves considerable boilerplate code and configuration. Tools like Create React App simplify the initial setup, but as projects grow, the complexity can increase, requiring additional configuration and understanding of build tools like Webpack and Babel.
  3. Rapidly Changing Environment:

    • The React ecosystem evolves quickly, with frequent updates and new tools emerging regularly. Keeping up with the latest best practices, updates, and libraries can be overwhelming for developers. This fast pace of change can also lead to issues with outdated documentation and compatibility between different libraries and versions.
  4. Poor SEO:

    • By default, React renders applications on the client side, which can lead to poor SEO performance because search engine crawlers might have difficulty indexing the dynamic content. Although solutions like server-side rendering (SSR) with frameworks like Next.js exist, implementing them adds complexity to the project.
  5. State Management Complexity:

    • Managing state in large React applications can become complex. While React's built-in state management works well for small applications, scaling up requires more sophisticated state management solutions like Redux, MobX, or the Context API. These solutions add another layer of complexity and require additional learning and setup.

The Synergy Between PHP and React in Modern Web Applications

The synergy between PHP and React in modern web applications leverages the strengths of both technologies to create robust, dynamic, and scalable applications. Here’s an in-depth look at how these technologies complement each other and the benefits of combining them:

5 Benefits of using PHP with React

Note: the benefits are more than five but here are the listed few!

1. Full-Stack Versatility

Frontend and backend integration:

  • Seamless Data Handling: React effectively manages the front end, while PHP can handle server-side logic and data exchanges, resulting in a coherent development environment.

  • API-Driven Development: By supplying data to the React frontend via GraphQL or RESTful endpoints, PHP may function as a potent backend API, allowing for a clear division of responsibilities.

Efficiency of Development:

  • Parallel Development: Teams working on front-end and back-end projects simultaneously can speed up development and eliminate bottlenecks.

  • reused Components: Frontend development is more modular and manageable because of React's component-based design, which guarantees that UI elements are reused.

2. Scalability

Managing a Higher Load:

  • Effective Backend: PHP frameworks like Laravel are designed to manage massive amounts of data and user requests effectively, handling intricate and scalable backend processes.

  • Frontend Optimisation: Even with intricate and data-intensive apps, React's virtual DOM and effective diffing technique guarantee quick and responsive UI changes.

Architecture of Microservices:

  • Modular Approach: Different services can scale independently when PHP is included in a microservices architecture. React facilitates scalability by allowing it to use these services as required.

  • Burden Distribution: The program as a whole can manage more traffic skillfully by dividing the burden between PHP, which handles server-side operations, and React, which handles client-side interactions.

3. Performance

Quick load times:

  • Server-Side Rendering (SSR): Initial HTML may be pre-rendered by PHP and sent to the client, thereafter React can hydrate it. This method boosts the user experience and speeds up the initial load time.

  • Asynchronous Data Fetching: By using React, data may be fetched from the PHP backend asynchronously, maintaining a responsive user interface and effective handling of data changes.

Enhanced Communication:

  • Effective State Management: React's state management features, such as context and hooks, enable better handling of UI state changes, which minimizes the need for pointless re-renders.

  • Caching and Optimisation: PHP can use server-side caching techniques to speed up the serving of static material and lower database demand, therefore improving performance.

4. Rich User Interfaces

UIs that are interactive and dynamic:

  • Component-Based design: React's component-based design enables programmers to create complex, interactive user interfaces that are simple to update and expand.

  • Real-Time Updates: React is capable of handling dynamic content changes and real-time updates with efficiency, making for a smooth and interesting user experience.

Improved User Experience:

  • Contemporary UI Libraries: React works nicely with contemporary UI libraries and frameworks (such as Material-UI and Ant Design), enabling programmers to design aesthetically pleasing and intuitive user interfaces.

  • Building responsive and adaptable user interfaces (UIs) that function effectively on a variety of devices and screen sizes is made simple using React.

5. SEO-Friendly

Better Optimisation for Search Engines:

  • Server-Side Rendering (SSR): Pre-rendering HTML content using PHP before providing it to the client guarantees better search engine indexing and SEO.

  • Meta Tags and Dynamic material: Using information from the PHP backend, React can dynamically manage and update meta tags, titles, and other SEO-relevant material.

Better Crawlability:

  • Static Site Generation (SSG): React may produce static pages at build time, improving the application's SEO while retaining PHP for dynamic content, by utilizing solutions like Next.js, which supports both SSR and SSG.

  • URL Structure: React can handle routing and navigation, making sure that visitors and search engines can explore the site with ease, while PHP can manage clear, SEO-friendly URL structures.

Developers may construct robust, scalable, and performance-optimized online apps with rich user experiences and search engine optimization by integrating PHP with React. Because of their synergy, frontend and backend technologies may be combined to create a strong and adaptable development process.


Creating a PHP and React Development Environment

At this point, we are about to start an actual project using React.js and PHP as the front end.

Prerequisites

There are things you need to know as a developer or things you need to have to be able to make php work as a backend with React. Here is the essential list!

  • Have Basic Knowledge of PHP
  • Know your React.Js
  • Make Sure Node.js accompanied by npm is installed on your machine.
  • Have PHP installed in your system Apache or Nginx

Step By Step Process On How To Use PHP As a Backend Using React As A Front-end

The step to use PHP as a backend alongside React is quite simple and it’s as follows.

Building The Frontend

Step 1: Open your terminal and run the following command below:

npx create-react-app my-react-app

Note: before running this command, you have to cd into the directory where you want your react folder to be! the way to cd to your desired directory is by adding this command to your terminal

cd Documents

After this, you’ll wait for your React app to be created.

Step 2: Navigate to your project folder:
The project you just created needs to be visited in the terminal

cd my-react-app

Step 3: Start the development server:

npm start

Building the PHP Backend
It's time to construct the PHP backend now that your React application is operational:

Step 1: Create a new folder for your PHP files within your React app directory.
to achieve this, run the following command on your terminal

mkdir php_backend

By running this command you’ll see a folder named php_backend

How To Use PHP As A Backend Using React For Frontend

Step 2: Inside the php-backend folder, create a file named index.php.
Note: you’re free to call it any name, in my case I decided to use the index.php.

How To Use PHP As A Backend Using React For Frontend

Step 3: In the index.php you can start defining your PHP endpoints and logic.
Below is what is written in my php-backend/index.php if you’re a PHP developer you’ll be familiar with this syntax.

Now the next thing to do is go to the React Code you created earlier and open the folder in your code editor you’ll see a folder like src/App.js and add this syntax below.

import React, { Component } from 'react';
 // import logo from './logo.svg';
import axios from 'axios'; //Import Axios
import './App.css';

class App extends Component{
state = {
  text : ""
}
handleAdd = async e =>{
 await this.setState({
   text : e.target.value
 }) 
}
handleSubmit = e =>{
 e.preventDefault();
 console.log(this.state.text);
 let formData = new FormData();
 formData.append("text", this.state.text);
 const url = "http://localhost:80/react-backend/"
 axios.post(url,formData)
 .then(res=> console.log(res.data))
 .catch(err=> console.log(err))
}
render(){
  return(
    

); }

}

export default App;

Note: what allows the PHP to work is the **Axios**. Look at the code snippet below you’ll see how we used it!

In the public folder of your project, you’ll see an index.html file in that file I added a bootstrap cdn as a framework I'm using,

So Here’s a little styling.

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
   animation: App-logo-spin infinite 20s linear;
  }
}

 .App-header {
   background-color: #282c34;
   min-height: 100vh;
   display: flex;
   flex-direction: column;
   align-items: center;
   justify-content: center;
   font-size: calc(10px   2vmin);
   color: white;
 }

 .App-link {
   color: #61dafb;
 }

 @keyframes App-logo-spin {
 from {
  transform: rotate(0deg);
 }
 to {
  transform: rotate(360deg);
 }
}

After trying all these here’s the view it will give to you.

How To Use PHP As A Backend Using React For Frontend

Her is the database controlling the backend. once you fill in the text and click save the text will display in the database automatically.

How To Use PHP As A Backend Using React For Frontend

hereafter I wrote **Freddie** and I clicked on Browse, in the top right corner of the image displayed below. Once you see this know that you have done the right thing.

How To Use PHP As A Backend Using React For Frontend

That’s the step I used in React and PHP in a single application.

Conclusion

In conclusion, integrating PHP as a backend with React as a frontend offers a robust and versatile solution for modern web application development. As discussed, this combination leverages the strengths of PHP's server-side capabilities and React's dynamic, component-based architecture to create scalable, high-performance applications. PHP efficiently handles server-side logic, database interactions, and API creation, while React ensures a rich, responsive user interface and seamless data handling.

This synergy between PHP and React not only enhances the development process but also results in web applications that are interactive, engaging, and SEO-friendly. Embracing this powerful integration empowers developers to build comprehensive and user-centric web applications with ease and efficiency.

I hope you found this tutorial incredibly valuable! Until next time, goodbye.

About The Author

Full-stack Laravel developer Emmanuel Okolie has 4 years of experience in software development. He has developed full-fledged skills by combining software development, writing, and instructing others in what he does.

His stacks include ReactJ, Laravel, PHP, JavaScript, and other languages and frameworks.
As a freelancer, he creates websites for clients and writes technical guides to show people how to do what he does.

If given the chance, Emmanuel Okolie would enjoy speaking with you. Please go to and follow him on his website, Facebook, Github, LinkedIn, and Twitter.

版本聲明 本文轉載於:https://dev.to/emmykolic/how-to-use-php-as-a-backend-using-react-for-frontend-3dca?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何使用預先匯入的套件啟動 python 或 ipython。
    如何使用預先匯入的套件啟動 python 或 ipython。
    不必每次執行 python 或 ipython 時都必須編寫“import os”或其他常見包,此腳本將啟動 python 並導入這些包 #!/usr/bin/env bash # -----------------------------------------------------------...
    程式設計 發佈於2024-11-06
  • python中的資料類型
    python中的資料類型
    內建資料型別 文字類型:字串 數值類型:int、float、complex 序列類型:清單、元組、範圍 映射類型:字典 集合類型:集合、凍結集合 布林類型:bool 二進位類型:位元組、位元組數組、記憶體視圖 無型別:無型別 程式 a=「阿維納什」 印刷(類型(a)) b=45 印刷(類型(b)) ...
    程式設計 發佈於2024-11-06
  • JavaScript 中的提升
    JavaScript 中的提升
    什么是 JavaScript 提升? 提升是指 JavaScript 中在执行之前进行声明的过程。首先处理变量和函数声明。因此,即使变量在声明之前被引用,也不会导致错误,而是返回 undefined。对于函数声明,整个函数被提升,这意味着它可以在代码中定义之前使用。此过程在执行开始...
    程式設計 發佈於2024-11-06
  • 如何在 Go 中同時選擇緩衝發送和無緩衝接收通道?
    如何在 Go 中同時選擇緩衝發送和無緩衝接收通道?
    同時選擇 Go 發送和接收通道在 Go 中,可以使用 select 語句在通道上執行非阻塞 I/O 操作。然而,在處理緩衝發送通道(chan
    程式設計 發佈於2024-11-06
  • 如何將列表列表轉換為統一的 NumPy 陣列?
    如何將列表列表轉換為統一的 NumPy 陣列?
    將清單清單轉換為NumPy 陣列資料分析中的一個常見任務是將清單清單轉換為NumPy 陣列高效率的數值運算。這個數組可以透過將每個列表分配給一行來形成,列表中的每個元素佔據一列。 選項 1:陣列陣列如果子清單有不同的長度,適當的方法是建立陣列的陣列。這保留了清單清單的原始結構,從而可以輕鬆檢索特定元...
    程式設計 發佈於2024-11-06
  • 前端的頂級設計模式
    前端的頂級設計模式
    在过去的几个月里,我为前端开发人员分享了一些流行的设计模式。其中包括 Singleton、Facade、Observer、Publisher/Subscriber 等模式。今天,我想总结一下这些模式的一些要点和好处,以及如何使用它们来改进您的前端开发流程。 什么是设计模式 设计模式是...
    程式設計 發佈於2024-11-06
  • ServBay版本.pdate公告
    ServBay版本.pdate公告
    我們很高興地宣布新版本 1.4.4 已經到來!讓我們來看看新增的備受期待的新功能。 新功能 CA和憑證管理: 統一SSL憑證管理平台:全新的憑證管理平台,旨在簡化憑證申請與管理流程。 ServBay User CA 和 ServBay Public CA: 引入 ...
    程式設計 發佈於2024-11-06
  • Spring框架中的控制反轉
    Spring框架中的控制反轉
    控制反转(IoC)和依赖注入(DI)是Spring框架中的两个基本概念。传统上,对象负责创建和管理它们自己的依赖关系。然而,IoC 通过将对象创建和依赖管理的控制权移交给像 Spring 这样的框架来翻转这一责任。 这种转变有几个优点: 更简单的实现交换:只需对代码库进行最小的更改即可交换不同的实现...
    程式設計 發佈於2024-11-06
  • 使用 React 建立遞歸檔案系統:深入探討
    使用 React 建立遞歸檔案系統:深入探討
    簡介:在 React 中建構遞歸檔案系統 在現代 Web 開發中,建立互動式動態檔案系統是常見的要求。無論是管理文件、組織專案或建構複雜的資料結構,擁有強大的文件系統都至關重要。在這篇文章中,我們將探討如何在 React 中建立遞歸檔案系統,並專注於可以新增、重新命名或刪除的嵌套資...
    程式設計 發佈於2024-11-06
  • SQL 查詢速度慢?使用此技術提高應用程式的效能
    SQL 查詢速度慢?使用此技術提高應用程式的效能
    挑戰 在我的應用程式(React Spring Boot Oracle)中,處理大型資料集導致處理時間極為緩慢。我需要一種解決方案來提高效能而不影響準確性或完整性。 解決方案:NTILE 並行處理 NTILE 是一個功能強大的 SQL 視窗函數,旨在將結果集劃分為...
    程式設計 發佈於2024-11-06
  • 關於測試覆蓋率的真相
    關於測試覆蓋率的真相
    一個強而有力的真理。 看下面這段簡單明了的程式碼: function sum(a, b) { return a b; } 現在,讓我們為它寫一些測試: test('sum', () => { expect(sum(1, 2)).toBe(3); expect(...
    程式設計 發佈於2024-11-06
  • 為什麼我的 OpenGL 三角形無法在 Go 中渲染?調查頂點緩衝區問題。
    為什麼我的 OpenGL 三角形無法在 Go 中渲染?調查頂點緩衝區問題。
    Go 中的OpenGL 頂點緩衝區問題在Go 中嘗試使用OpenGL 顯示三角形時,使用者遇到了頂點緩衝區問題緩衝區無法渲染形狀。 Go 程式碼源自於教程,但與 C 程式碼不同的是,它沒有產生任何輸出。 問題原因問題的根本原因位於傳遞給 vertexAttrib.AttribPointer() 的參...
    程式設計 發佈於2024-11-06
  • 為什麼在 Linux 32 位元發行版上的 Go 程式中設定 `ulimit -n` 會導致「參數無效」錯誤?
    為什麼在 Linux 32 位元發行版上的 Go 程式中設定 `ulimit -n` 會導致「參數無效」錯誤?
    如何在 Go 程式中設定 ulimit -n? 問題使用者嘗試在 Go 程式中設定 ulimit -n使用 setrlimit 和 getrlimit 系統呼叫將其限制在程式內而不是全域。然而,在嘗試設定該值時出現錯誤,提示「參數無效」。 解決方案發現問題是由於 Linux 32 的 Getrlim...
    程式設計 發佈於2024-11-06
  • 如何在Python中創建無限深度的動態嵌套字典?
    如何在Python中創建無限深度的動態嵌套字典?
    未定義深度的動態嵌套字典在涉及複雜多層資料結構的場景中,經常會遇到變數嵌套字典的需求水平。雖然硬編碼插入語句是一種潛在的解決方案,但當事先未知嵌套深度時,這種方法是不切實際的。 要克服此限制,請考慮利用 Python 的 collections.defaultdict,它允許動態建立字典。可以使用下...
    程式設計 發佈於2024-11-06
  • Python 變得強大:輕鬆程式設計的初學者指南
    Python 變得強大:輕鬆程式設計的初學者指南
    Python 是一門強大的程式語言,文法簡單,應用廣泛。安裝 Python 後,可以學習其基本語法,包括變數賦值、資料類型和流程控制。實戰案例中,我們透過蒙特卡羅模擬計算圓周率,展示了 Python 在數值計算中的能力。此外,Python 擁有豐富的函式庫,涵蓋機器學習、資料分析和網路開發等領域,體...
    程式設計 發佈於2024-11-06

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3