{"id":21868537,"url":"https://github.com/ssl/aapje.php","last_synced_at":"2025-04-14T22:42:16.964Z","repository":{"id":264707781,"uuid":"893993930","full_name":"ssl/aapje.php","owner":"ssl","description":"A lightweight, single-file PHP framework for building simple APIs.","archived":false,"fork":false,"pushed_at":"2024-11-30T15:52:07.000Z","size":54,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-28T10:50:28.790Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ssl.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"license.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-11-25T15:07:59.000Z","updated_at":"2025-02-15T09:52:08.000Z","dependencies_parsed_at":"2024-11-25T22:41:37.321Z","dependency_job_id":null,"html_url":"https://github.com/ssl/aapje.php","commit_stats":null,"previous_names":["ssl/aapje.php"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssl%2Faapje.php","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssl%2Faapje.php/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssl%2Faapje.php/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ssl%2Faapje.php/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ssl","download_url":"https://codeload.github.com/ssl/aapje.php/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248975332,"owners_count":21192197,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-28T05:14:03.494Z","updated_at":"2025-04-14T22:42:16.947Z","avatar_url":"https://github.com/ssl.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# aapje.php\n\n**aapje.php** is a lightweight, single-file PHP framework designed for building simple and efficient APIs. It offers essential features such as routing, database interactions, middleware support, CORS handling, and utility helper functions, all while maintaining a minimalistic and easy-to-use structure.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://img.shields.io/github/release/ssl/aapje.php?style=flat\"\u003e\n  \u003cimg src=\"https://img.shields.io/github/issues/ssl/aapje.php?style=flat\"\u003e\n  \u003cimg src=\"https://img.shields.io/github/forks/ssl/aapje.php?style=flat\"\u003e\n  \u003cimg src=\"https://img.shields.io/github/stars/ssl/aapje.php?style=flat\"\u003e\n  \u003cimg src=\"https://img.shields.io/github/license/ssl/aapje.php?style=flat\"\u003e\n  \u003cbr\u003e\u003cbr\u003e\n  \u003cb\u003e⚠️ aapje.php is currently in beta. bugs or other issues can be expected. do not use in production. ⚠️\u003c/b\u003e\n\u003c/p\u003e\n\n## 🚀 Features\n\n- **Routing:** Define routes with dynamic parameters supporting various HTTP methods.\n- **Database Integration:** Simplified PDO-based database interactions with CRUD operations.\n- **Middleware Support:** Execute custom logic before or after route handling.\n- **CORS Support:** Built-in Cross-Origin Resource Sharing configuration for secure API access.\n- **Helpers Class:** Utility functions to streamline common tasks.\n- **Single-File Architecture:** Easy setup and deployment without external dependencies.\n\n## 📦 Installation\n\n1. **Download `aapje.php`**\n\n2. **Include in Your Project:**\n\n   Place `aapje.php` in your project directory and include it in your PHP scripts.\n\n   ```php\n   \u003c?php\n   require 'aapje.php';\n   ```\n\n3. **Web Server Configuration:**\n\n   Ensure that all requests to your website (or specific folder) using `aapje.php` are passed through your routing file.\n\n   ```apache\n   # Example Apache .htaccess file\n   RewriteEngine On\n   RewriteRule ^(.*)$ index.php [L]\n   ```\n\nAlternatively, you can fork or clone this repository, sync it to a web host, and directly start coding your API inside the `index.php` file.\n\n## 🛠️ Configuration\n\nConfiguration is optional and **aapje.php** can operate without a database. CORS is disabled by default. When enabling CORS by setting `'enabled'` to `true`, the `origins`, `headers`, and `methods` will default to `'*'` unless explicitly specified.\n\nConfigure **aapje.php** using the `setConfig` method. You can set database credentials, CORS settings, and default headers.\n\n```php\naapje::setConfig([\n    'database' =\u003e [\n        'host' =\u003e 'localhost',\n        'dbname' =\u003e 'your_database',\n        'user' =\u003e 'your_username',\n        'password' =\u003e 'your_password',\n    ],\n    'cors' =\u003e [\n        'enabled' =\u003e true,\n        'origins' =\u003e ['https://example.com', 'https://example.org'], // Allowed origins\n        'methods' =\u003e ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed methods\n        'headers' =\u003e ['Content-Type', 'Authorization'], // Allowed headers\n        'credentials' =\u003e true, // Allow credentials\n    ],\n    'default_headers' =\u003e [\n        'X-Powered-By' =\u003e 'aapje.php',\n    ],\n]);\n```\n\n## 📚 Usage\n\n### 1. **Defining Routes**\n\nDefine routes using the `route` method, specifying the HTTP method, URL pattern, and callback function.\n\n```php\n// Responds to all HTTP methods\naapje::route('*', '/', function () {\n    aapje::response()-\u003eecho(['message' =\u003e 'Welcome to aapje.php!']);\n});\n\n// GET route with dynamic parameter\naapje::route('GET', '/user/@id', function ($id) {\n    $user = aapje::select('users', '*', ['id' =\u003e $id]);\n    if ($user) {\n        aapje::response()-\u003eecho($user);\n    } else {\n        aapje::response()-\u003estatusCode(404)-\u003eecho(['error' =\u003e 'User not found']);\n    }\n});\n```\n\n### 2. **Using Middleware**\n\nRegister middleware functions to execute custom logic before route handling, such as logging or authentication.\n\n```php\n// Define a middleware function\nfunction loggingMiddleware($request, $response) {\n    $method = $_SERVER['REQUEST_METHOD'];\n    $uri = $_SERVER['REQUEST_URI'];\n    $ip = $request-\u003eip();\n    error_log(\"[$method] $uri from $ip\");\n}\n\n// Register the middleware\naapje::middleware('loggingMiddleware');\n```\n\n### 3. **Utilizing Helpers**\n\nUse the `Helpers` class for common utility functions like escaping HTML or handling files.\n\n```php\naapje::route('GET', '/escape', function () {\n    $unsafeString = '\u003cscript\u003ealert(\"XSS\")\u003c/script\u003e';\n    $safeString = Helpers::esc($unsafeString);\n    aapje::response()-\u003eecho(['escaped' =\u003e $safeString]);\n});\n```\n\n### 4. **Handling CORS**\n\nCORS settings are managed via the `setConfig` method. When enabled, **aapje.php** automatically sets the necessary headers and handles preflight `OPTIONS` requests.\n\n```php\naapje::setConfig([\n    'cors' =\u003e [\n        'enabled' =\u003e true,\n        'origins' =\u003e ['https://example.com'], // Allowed origins\n        'methods' =\u003e ['GET', 'POST'], // Allowed HTTP methods\n        'headers' =\u003e ['Content-Type', 'Authorization'], // Allowed headers\n        'credentials' =\u003e true, // Allow credentials\n    ],\n]);\n\n// Example route to test CORS\naapje::route('*', '/cors-test', function () {\n    aapje::response()-\u003eecho(['message' =\u003e 'CORS is configured properly!']);\n});\n```\n\n### 5. **Database Operations**\n\nPerform CRUD operations using built-in methods. Below is an example that demonstrates creating, reading, updating, and deleting a user, along with setting custom headers and handling advanced database queries like sorting and limiting results.\n\n```php\n// Create a new user\naapje::route('POST', '/user', function () {\n    $input = aapje::request()-\u003einput();\n    $data = [\n        'name' =\u003e $input['name'] ?? null,\n        'email' =\u003e $input['email'] ?? null,\n    ];\n\n    if (!$data['name'] || !$data['email']) {\n        aapje::response()-\u003estatusCode(400)-\u003eecho(['error' =\u003e 'Name and email are required']);\n    }\n\n    try {\n        $id = aapje::insert('users', $data);\n        aapje::response()-\u003estatusCode(201)-\u003eecho(['created_user_id' =\u003e $id]);\n    } catch (Exception $e) {\n        aapje::response()-\u003estatusCode(500)-\u003eecho(['error' =\u003e 'Failed to create user']);\n    }\n});\n\n// Retrieve all users with sorting and limit\naapje::route('GET', '/users', function () {\n    $users = aapje::selectAll('users', '*', [], [\n        'orderBy' =\u003e 'name',\n        'sort' =\u003e 'ASC',\n        'limit' =\u003e 10\n    ]);\n    aapje::response()-\u003eheader('X-Custom-Header', 'CustomValue')-\u003eecho($users);\n});\n\n// Update a user\naapje::route('PUT', '/user/@id', function ($id) {\n    $input = aapje::request()-\u003einput();\n    $data = [\n        'name' =\u003e $input['name'] ?? null,\n        'email' =\u003e $input['email'] ?? null,\n    ];\n\n    if (!$data['name'] \u0026\u0026 !$data['email']) {\n        aapje::response()-\u003estatusCode(400)-\u003eecho(['error' =\u003e 'At least one of name or email is required']);\n    }\n\n    try {\n        aapje::update('users', $data, ['id' =\u003e $id]);\n        aapje::response()-\u003eecho(['message' =\u003e 'User updated successfully']);\n    } catch (Exception $e) {\n        aapje::response()-\u003estatusCode(500)-\u003eecho(['error' =\u003e 'Failed to update user']);\n    }\n});\n\n// Delete a user\naapje::route('DELETE', '/user/@id', function ($id) {\n    try {\n        aapje::delete('users', ['id' =\u003e $id]);\n        aapje::response()-\u003eecho(['message' =\u003e 'User deleted successfully']);\n    } catch (Exception $e) {\n        aapje::response()-\u003estatusCode(500)-\u003eecho(['error' =\u003e 'Failed to delete user']);\n    }\n});\n```\n\nFor more comprehensive examples, refer to the [`examples.php`](https://github.com/ssl/aapje.php/blob/main/examples.php) file in the repository.\n\n## 🔧 API Reference\n\n### **aapje Class**\n\n- **`setConfig(array $config)`**\n\n  Set global configuration options.\n\n- **`route(string $method, string $pattern, callable $callback)`**\n\n  Define a new route.\n\n- **`middleware(callable $callback)`**\n\n  Register a middleware function.\n\n- **`run()`**\n\n  Start processing incoming requests.\n\n- **Database Methods:**\n\n  - **`insert(string $table, array $data)`**: Insert a new record.\n  - **`update(string $table, array $data, array $conditions = [])`**: Update existing records.\n  - **`delete(string $table, array $conditions = [])`**: Delete records.\n  - **`select(string $table, $columns = '*', array $conditions = [], array $options = [])`**: Select a single record.\n  - **`selectAll(string $table, $columns = '*', array $conditions = [], array $options = [])`**: Select multiple records.\n\n### **Request Class**\n\n- **`header(string $key): ?string`**: Retrieve a specific request header.\n- **`headers(): array`**: Get all request headers.\n- **`input(bool $decode = true, bool $associative = true)`**: Get JSON input from the request body.\n- **`getParam(string $key): ?string`**: Retrieve a specific GET parameter.\n- **`getParams(): array`**: Get all GET parameters.\n- **`postParam(string $key): ?string`**: Retrieve a specific POST parameter.\n- **`postParams(): array`**: Get all POST parameters.\n- **`ip(): string`**: Get the client's IP address.\n- **`userAgent(): ?string`**: Get the client's User-Agent.\n\n### **Response Class**\n\n- **`header(string $key, string $value): self`**: Set a response header.\n- **`headers(array $headers): self`**: Set multiple response headers.\n- **`cookie(string $name, string $value, array $options = []): self`**: Set a cookie.\n- **`cookies(array $cookies): self`**: Set multiple cookies.\n- **`statusCode(int $code): self`**: Set the HTTP status code.\n- **`echo($content, bool $json = true)`**: Send the response to the client.\n\n### **Helpers Class**\n\n- **`esc(string $string): string`**: Escape HTML special characters.\n- **`getFile(string $file): string`**: Get the contents of a file.\n- **`putFile(string $file, string $content): void`**: Write content to a file.\n\n## 📄 License\n\n**aapje.php** is open-source software licensed under the [MIT License](https://github.com/ssl/aapje.php/blob/main/license.txt).\n\n---\n\nFeel free to contribute to **aapje.php** by submitting issues or pull requests.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fssl%2Faapje.php","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fssl%2Faapje.php","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fssl%2Faapje.php/lists"}