Home >Backend Development >PHP Tutorial >Integrating PHP with React Using Lithe

Integrating PHP with React Using Lithe

Susan Sarandon
Susan SarandonOriginal
2024-10-25 07:37:18645browse

Integrando o PHP com React Usando o Lithe

In this post, we will learn how to integrate the Lithe framework with the React library, highlighting how Lithe integrates perfectly with frontend libraries. In addition to being excellent for building APIs, Lithe makes it easy to access your application's resources, configuring CORS (Cross-Origin Resource Sharing) efficiently to ensure that your applications communicate securely and effectively.

Step 1: Configuring the Environment

1. Lithe Installation

First, install Lithe if you haven't already. Run the following command in the terminal:

composer create-project lithephp/lithephp nome-do-projeto
cd nome-do-projeto

2. Installing React

Then create a new React project within your Lithe project. Run:

npx create-react-app frontend
cd frontend

Step 2: Installing and Configuring CORS

1. Installing the CORS Module

To use CORS middleware in your Lithe project, you need to install the lithemod/cors package. Run the following command:

composer require lithemod/cors

2. Using CORS Middleware

After installation, you must configure CORS middleware in your Lithe application. Open the main file src/App.php and add the following code:

If you want to allow multiple sources to access your API, configure CORS as follows:

use Lithe\Middleware\Configuration\cors;

$app = new \Lithe\App;

$app->use(cors(['origins' => '*']));

$app->listen();

On the other hand, if you want only your React application to consume the API, use the following configuration:

$app->use(cors(['origins' => 'http://localhost:3000']));

Step 3: Configuring the Backend with Lithe

1. Creating an API Route

In your Lithe project, create a new router to provide data to React. Create a route file, like src/routes/api.php:

use Lithe\Http\{Request, Response};
use function Lithe\Orbis\Http\Router\{get};

get('/data', function(Request $req, Response $res) {
    $data = [
        'message' => 'Hello from Lithe!',
        'items' => [1, 2, 3, 4, 5],
    ];
    return $res->json($data);
});

After defining the route file, you must add the router in your Lithe application. Open the main src/App.php file again and add the following code before calling the listen method:

// ...

use function Lithe\Orbis\Http\Router\router;

$apiRouter = router(__DIR__ . '/routes/api');

$app->use('/api', $apiRouter);

// ...

The src/App.php file would look like this:

use Lithe\Middleware\Configuration\cors;
use function Lithe\Orbis\Http\Router\router;

$app = new \Lithe\App;

$app->use(cors(['origins' => '*']));

$apiRouter = router(__DIR__ . '/routes/api');

$app->use('/api', $apiRouter);

$app->listen();

2. Testing the Route

Start the Lithe server with the following command:

php line serve

Visit http://localhost:8000/api/data to ensure JSON is returned correctly.

Step 4: Configuring the Frontend with React

1. Consuming the API in React

Open the src/App.js file in your React project and replace the content with:

import React, { useEffect, useState } from 'react';

function App() {
    const [data, setData] = useState(null);

    useEffect(() => {
        fetch('http://localhost:8000/api/data')
            .then(response => response.json())
            .then(data => setData(data))
            .catch(error => console.error('Error fetching data:', error));
    }, []);

    return (
        <div>
            <h1>Integrando o PHP com React usando Lithe</h1>
            {data ? (
                <div>
                    <p>{data.message}</p>
                    <ul>
                        {data.items.map((item, index) => (
                            <li key={index}>{item}</li>
                        ))}
                    </ul>
                </div>
            ) : (
                <p>Carregando...</p>
            )}
        </div>
    );
}

export default App;

2. Starting React Server

To start the React development server, run:

composer create-project lithephp/lithephp nome-do-projeto
cd nome-do-projeto

Step 5: Verifying Integration

Go to http://localhost:3000 in your browser. You should see the message "Hello from Lithe!" and a list of items returned by the API.

Final Considerations

With this, you have successfully integrated Lithe with React and configured CORS to allow only the React application to access backend resources or allow multiple sources as needed. Now you can expand your application as you wish.

Feel free to share your experiences and questions in the comments!

The above is the detailed content of Integrating PHP with React Using Lithe. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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