...
Website

Guide to Creating a REST API with KumbiaPHP and Workerman PHP Connected to PostgreSQL

This guide will help you create a REST API using KumbiaPHP and Workerman PHP, connected to a PostgreSQL database. We will cover the following operations:

  1. Querying all data in the users table (fields: username and email).
  2. Updating the email based on username.
  3. Deleting data based on username.

1. Install KumbiaPHP

Start by setting up a new KumbiaPHP project:

composer create-project kumbia/kumbia my-project
cd my-project

2. Configure PostgreSQL Connection

Configure the database connection by editing the config/database.php file. Replace the default configuration with your PostgreSQL credentials:

<?php

return [
    'default' => 'pgsql',
    'pgsql' => [
        'dsn' => 'pgsql:host=localhost;port=5432;dbname=your_database_name',
        'username' => 'your_username',
        'password' => 'your_password',
        'options' => [],
    ],
];

3. Create the User Model

Create a model for the users table. Create the file app/models/User.php:

<?php

class User extends ActiveRecord {

    public function initialize() {
        // Optional: Add validation or other initialization code
    }

}

4. Create the REST API Controller

Create a controller to handle the API endpoints. Create the file app/controllers/ApiController.php:

<?php

class ApiController extends AppController {

    public function initialize() {
        View::select(null, null); // Disable view rendering
        $this->response->setContentType('application/json');
    }

    // 1. Query all data in the users table
    public function users() {
        $users = User::all();
        echo json_encode($users->toArray(['username', 'email']));
    }

    // 2. Update email based on username
    public function update_email($username) {
        $user = User::find_first("username = '$username'");
        if ($user) {
            $email = Input::request('email');
            if ($email) {
                $user->email = $email;
                if ($user->save()) {
                    echo json_encode(['message' => 'Email updated successfully']);
                }
            } else {
                echo json_encode(['error' => 'Email is required']);
            }
        } else {
            echo json_encode(['error' => 'User not found']);
        }
    }

    // 3. Delete data based on username
    public function delete_user($username) {
        $user = User::find_first("username = '$username'");
        if ($user) {
            if ($user->delete()) {
                echo json_encode(['message' => 'User deleted successfully']);
            }
        } else {
            echo json_encode(['error' => 'User not found']);
        }
    }
}

5. Define Routes

The routes are defined in the config/routes.php file. Add the following routes:

Router::connect('/api/users', 'api@users');
Router::connect('/api/update-email/{username}', 'api@update_email');
Router::connect('/api/delete-user/{username}', 'api@delete_user');

6. Run the Application with Workerman

To run the KumbiaPHP application using Workerman, create a start.php script:

<?php

use Workerman\Worker;
use Workerman\Connection\TcpConnection;

require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('http://0.0.0.0:8787');
$worker->count = 4;

$worker->onMessage = function(TcpConnection $connection, $data) {
    ob_start();
    require_once __DIR__ . '/index.php';
    $output = ob_get_clean();
    $connection->send($output);
};

Worker::runAll();

Start the Workerman server with the following command:

php start.php start

7. Test the API

  • Query all users: Send a GET request to http://localhost:8787/api/users.
  • Update email: Send a POST request to http://localhost:8787/api/update-email/{username} with the following JSON body:
  {
    "email": "[email protected]"
  }
  • Delete user: Send a DELETE request to http://localhost:8787/api/delete-user/{username}.

This setup provides a basic REST API using KumbiaPHP and Workerman PHP connected to PostgreSQL. You can expand the functionality as needed for your project.

Leave a Reply

Your email address will not be published. Required fields are marked *