Introduction 導入 ダイナミックでインタラクティブなウェブアプリケーションの開発は、ダイナミックで常に変化するウェブ開発の世界で重要です。ユーザーインターフェースを作成するためのJavaScriptツールキットであるReactのスピードと多様性は、その大きな人気につながりました。しかし、PHPはまだサーバー側のプログラミングの強力なオプションです。このチュートリアルは、PHPバックエンドとReactフロントエンドの機能を簡単に組み合わせ、それぞれの強みを完全に活用する方法を示します。 Understanding the Distinct Roles of PHP and React PHPとReactの異なる役割を理解 What Is PHP? PHPって何? PHP は Hypertext Preprocessor の略で、Web 開発に使用されるサーバー側のスクリプト言語です。 HTML ファイルと簡単に組み込むことができます。 HTML コードは PHP ファイルにも書くことができます。 Merits Of PHP PHPの利点 以下は、PHPのいくつかの利点です。 Ease of Learning and Use: PHPは、初心者にとって比較的簡単なシンタクスで知られています。このシンプルさは、新しい開発者がWebアプリケーションを迅速に構築し始めるのに役立ちます。 Wide Adoption and Community Support: PHP には広く活発なコミュニティがあり、膨大なドキュメント、多くのチュートリアル、豊富なオンラインリソースが含まれています。コミュニティサポートはまた、広大な事前書かれたコード、フレームワーク、プラグインライブラリに翻訳されます。 Integration Capabilities: PHPは、さまざまなデータベース(MySQL、PostgreSQL、SQLite)、Webサーバー(Apache、Nginxなど)、その他のサービスとシームレスに統合されます。 Open Source: PHP は自由に使用し、配布することができるため、特に小規模企業やスタートアップにとって、開発コストが低下します。 Cross-Platform Compatibility: PHP は、Windows、Linux、macOS を含む複数のプラットフォームで実行できます。この柔軟性により、PHP アプリケーションは互換性の問題なしにさまざまな環境で展開できます。 Demerits Of PHP PHPのデメーター 以下はPHPのいくつかです。 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 ( vs ) parameter orders ( ) vs. ). This inconsistency can lead to confusion and errors, especially for new developers. str_replace strpos array_filter($array, $callback array_map($callback, $array) Historical Security Issues: PHP has a history of security vulnerabilities, partly due to its widespread use and partly due to its design. While modern PHP has significantly improved in terms of security features, legacy codebases and bad practices from earlier versions can still pose security risks. 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. 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 ( It is true, but it is false. This can be problematic, especially for large, complex codebases. "123" == 123 "123" === 123 5. Over-Reliance on Older, Procedural Code: 多くのPHPアプリケーションやチュートリアルでは、現代の、オブジェクト指向または機能的なプログラミング慣行の代わりに、古い手順プログラミングテクニックを使用しています。 What Is React? 反応って何? React JS は、ユーザー インターフェイスを構築するための宣言型、効率的で柔軟な JavaScript ライブラリです. It's 'V' in MVC. ReactJS は、アプリケーションのビュー レイヤーのみを担当するオープンソース、コンポーネントベースのフロントエンド ライブラリです. It isined by Facebook. Merits Of React Js React JSの利点 以下は React.js のいくつかの利点です。 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. 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. 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. 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. 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 React Jsの特徴 以下は React.js のいくつかです。 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. 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. 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. 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. 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(現代のWebアプリケーションにおけるPHPとReactの連携) 現代のWebアプリケーションにおけるPHPとReactの連携は、両方のテクノロジーの強みを活用して、強力でダイナミックでスケーラブルなアプリケーションを作成します。 5 Benefits of Using PHP with React React と PHP を使用する 5 つの利点 注:利点は5つ以上ありますが、ここではいくつかリストされています! 1. Full-Stack Versatility 1. Full Stack Versatility フロントとバックエンドの統合: シームレスなデータ処理: React はフロントエンドを効果的に管理し、PHP はサーバー側の論理とデータ交換を処理し、一貫した開発環境をもたらします。 API ドライブ開発: GraphQL または RESTful エンドポイントを通じて React フロントエンドにデータを提供することで、PHP は強力なバックエンド API として機能し、責任の明確な分割を可能にします。 Efficiency of Development: 並行開発:フロントエンドとバックエンドプロジェクトを同時に実行するチームは、開発を加速し、ボトルネックを取り除くことができます。 再利用コンポーネント:Frontendの開発は、Reactのコンポーネントベースの設計により、よりモジュール的で管理可能で、UI要素が再利用されることを保証します。 2. Scalability 2.スケーラビリティ Managing a Higher Load: 効果的なバックエンド:LaravelのようなPHPフレームワークは、膨大な量のデータとユーザーリクエストを効果的に管理し、複雑でスケーラブルなバックエンドプロセスを処理するように設計されています。 フロントエンド最適化:複雑でデータ密集型のアプリケーションでさえも、Reactの仮想DOMと効果的なディフィングテクニックは、迅速かつ応答性の高いUI変更を保証します。 Architecture of Microservices: モジュラーアプローチ: PHP がマイクロサービスアーキテクチャに組み込まれた場合、さまざまなサービスが独立してスケールできます。 負荷配布:プログラム全体では、サーバー側の操作を処理するPHPと、クライアント側の相互作用を処理するReactの間で負荷を分担することによって、より巧妙にトラフィックを管理することができます。 3. Performance 3.パフォーマンス Quick load times: Server-Side Rendering (SSR): 初期の HTML は PHP によってプレーレンダリングされ、クライアントに送信されることがあります。 Asynchronous Data Fetching: React を使用することで、PHP バックエンドからデータを非同期的に取得し、応答性の高いユーザーインターフェイスを維持し、データの変更を効果的に処理できます。 Enhanced Communication: 効率的なステータス管理: コンテキストやハックなどのReactのステータス管理機能は、UIステータス変更のより良い処理を可能にし、無意味なリレンダーの必要性を最小限に抑える。 キャッシングと最適化:PHPはサーバー側のキャッシング技術を使用して静的材料の配信を加速し、データベースの需要を低下させ、したがってパフォーマンスを向上させることができます。 Rich User Interfaces 豊富なユーザーインターフェイス UIs that are interactive and dynamic: React のコンポーネントベースの設計により、プログラマーは、更新と拡張が簡単で複雑でインタラクティブなユーザーインターフェイスを構築することができます。 Component-Based design: React は、ダイナミックなコンテンツ変更とリアルタイムの更新を効率的に処理し、スムーズで興味深いユーザーエクスペリエンスを提供します。 Real-Time Updates: Improved User Experience: Contemporary UI Libraries: React は、現代の UI ライブラリやフレームワーク (Material-UI および Ant Design など) で素晴らしく機能し、プログラマーが美学的に快適で直感的なユーザーインターフェイスを設計できるようにします。 さまざまなデバイスとスクリーンサイズで効果的に機能する応答性と適応性のあるユーザーインターフェイス(UI)の構築は、Reactを使用してシンプルにできます。 5. SEO-Friendly 5.SEOフレンドリー Better Optimization for Search Engines: サーバーサイドレンダリング(SSR):クライアントに提供する前にPHPを使ってHTMLコンテンツをプレレンダリングすることは、より良い検索エンジンインデックスとSEOを保証します。 Meta タグとダイナミック マテリアル:PHP バックエンドからの情報を使用して、React はダイナミックにメタタグ、タイトル、およびその他の SEO 関連のマテリアルを管理し、更新することができます。 Better Crawlability: Static Site Generation (SSG): React はビルドタイムで静的なページを生成し、アプリケーションの SEO を向上させながら、SSR と SSG を両方サポートする Next.js のようなソリューションを使用して、ダイナミックなコンテンツのための PHP を保持します。 URL 構造:React はルーティングとナビゲーションを処理し、訪問者や検索エンジンが簡単にサイトを探索できるようにしますが、PHP は明確でSEO フレンドリーな URL 構造を管理できます。 開発者は、PHPとReactを統合することによって、豊富なユーザー体験と検索エンジン最適化を備えた強力でスケーラブルでパフォーマンス最適化されたオンラインアプリケーションを構築することができます。 Creating a PHP and React Development Environment PHPとReact開発環境の構築 この時点で、React.js と PHP をフロントエンドとして使用する実際のプロジェクトを開始する予定です。 Prerequisites 前提条件 あなたが開発者として知る必要があるものや、PHPをReactでバックエンドとして機能させるために必要なものがあります。 PHPの基本的な知識 あなたのReact.jsを知る Make Sure Node.js, accompanied by npm, is installed on your machine. node.js があなたのマシンにインストールされていることを確認してください。 PHP が Apache または Nginx にインストールされています。 Step By Step Process On How To Use PHP As A Backend Using React As A Front-end Step by step process on how to use PHP as a backend using react as a front-end をバックエンドとして使用する方法 React と共に PHP をバックエンドとして使用するステップは、かなりシンプルで、以下の通りです。 Building The Frontend ターミナルを開いて、以下のコマンドを実行します。 Step 1: npx create-react-app my-react-app 注:このコマンドを実行する前に、あなたはあなたのReactフォルダが欲しい場所のディレクトリにCDをCDする必要があります! あなたの望むディレクトリにCDする方法は、あなたのターミナルにこのコマンドを追加することです。 cd Documents その後、Reactアプリが作成されるのを待つことになります。 プロジェクト フォルダに移動します. The project you just created needs to be visited in the terminal. あなたが作成したプロジェクトは、端末で訪問する必要があります。 Step 2: cd my-react-app 開発サーバーを起動する: Step 3: npm start Building the PHP Backend あなたのReactアプリケーションが稼働している今、PHPバックエンドを構築する時間です。 React アプリケーションディレクトリ内の PHP ファイルの新しいフォルダを作成します。これを実行するには、次のコマンドをターミナルで実行してください。 Step 1: mkdir php_backend このコマンドを実行すると、 php_backend という名前のフォルダが表示されます。 php バックエンド フォルダ内で、名前のファイルを作成する 注:あなたはそれを任意の名前と呼ぶ自由です. 私の場合、私は使用することを決めた。 . Step 2: index.php index.php IN THE あなたはあなたのPHPエンドポイントと論理を定義し始めることができます。 あなたがPHP開発者であれば、このシンタクスに精通しています。 Step 3: index.php php-backend/index.php <?PHP $serverName="localhost"; $userName="root"; $password=""; $databaseName="react_php"; $conn = mysqli_connect($serverName, $userName, $password, $databaseName); $recText = $_POST['text']; $query = ("INSERT INTO react_php (texts) VALUES('$recText')"); if (mysqli_query($conn, $query)) { echo "Data has been inserted successfully"; }else { echo "Error"; } ?> 次にやるべきことは、以前作成した React Code にアクセスして、コード エディターでフォルダを開くことです。 , and add this syntax below. このシンタックスを下に追加します。 src/App.js 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( <div className="App-header"> <input onChange={this.handleAdd} className="form-control" // value={this.state.text} type="text" id='text' placeholder='Enter Some Text!'/> <br/> <button onClick={this.handleSubmit} className="btn btn-success" id='submit'> Save</button> </div> ); } } export default App; 注:PHPが働くことを可能にするのは、 下のコードのスナップをご覧ください! どのように使われているかご覧ください! Axios あなたのプロジェクトの公開フォルダでは、あなたは1 そのファイルに、私が使用しているフレームワークとしてBootstrap CDNを追加しました。 index.html <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"> こちらはちょっとしたスタイリングです。 .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); } } これらすべてを試してみると、あなたが見る視点がここにあります。 ここにバックエンドを制御するデータベースがあります。テキストを記入して保存をクリックすると、テキストがデータベースに自動的に表示されます。 後日、書きました。 下の画像の右上隅に「ブラウス」をクリックすると、これを見ると、あなたが正しいことをしたことを知ってください。 Freddie それが React と PHP で 1 つのアプリケーションで使用したステップです。 Conclusion 結論 結論として、バックエンドとしてPHPとフロントエンドとしてReactを統合すると、近代的なWebアプリケーション開発のための強力で多様なソリューションが提供されます。前述したように、この組み合わせはPHPのサーバー側機能とReactのダイナミックなコンポーネントベースのアーキテクチャの強みを活用し、スケーラブルで高性能なアプリケーションを作成します。 このPHPとReactの連携は、開発プロセスを強化するだけでなく、インタラクティブで魅力的でSEOフレンドリーなWebアプリケーションも生み出します。 このチュートリアルがすごく役に立った!次回までお別れ。 About The Author 著者について フルスタックLaravel開発者 ハイ 彼は、ソフトウェア開発、書くこと、そして彼のやっていることを他の人に教えることによって、完全なスキルを開発してきました。 Emmanuel Okolie 4+ 彼のステッカーは、 で、 で、 で、 フリーランサーとして、彼はクライアント向けのウェブサイトを作成し、彼が行うことを人々に示すための技術ガイドを書きます。 ReactJS Laravel PHP JavaScript 機会があれば、 楽しみにしてくださる方、ぜひご一緒にご参加ください。 フェイスブック、 で、 そして、 . Emmanuel Okolie サイト GitHub リンク Twitterについて