https://github.com/nextphp-projects/rest
Provides tools for building and managing RESTful APIs, enabling easy creation, reading, updating, and deletion of resources over HTTP.
https://github.com/nextphp-projects/rest
Last synced: 27 days ago
JSON representation
Provides tools for building and managing RESTful APIs, enabling easy creation, reading, updating, and deletion of resources over HTTP.
- Host: GitHub
- URL: https://github.com/nextphp-projects/rest
- Owner: nextphp-projects
- License: mit
- Created: 2024-06-28T14:04:23.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-07-04T08:39:56.000Z (about 2 years ago)
- Last Synced: 2025-10-14T05:08:41.380Z (9 months ago)
- Language: PHP
- Size: 24.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# NextPHP Rest Package
The [NextPHP Rest](https://packagist.org/packages/nextphp/rest) package provides powerful routing capabilities and HTTP handling for PHP developers. This package supports all RESTful methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE, CONNECT, PRI) and various response formats such as JSON, XML, HTML, TEXT, and CSV. It simplifies the creation of APIs by allowing developers to define routes and controllers using attributes, ensuring a clean and efficient codebase.
This package is part of the [NextPHP Framework](https://github.com/nextphp-projects/nextphp), a modern and lightweight PHP framework designed for performance and scalability. [NextPHP](https://nextphp.io) aims to provide a comprehensive suite of tools and libraries to streamline the development process.
## Features
- Support for all RESTful methods (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE, CONNECT, PRI)
- Response formats: JSON, XML, HTML, TEXT, CSV
- Attribute-based route definitions
- Middleware support
- Easy integration with existing projects
## Installation
### Installing via Composer
To install the NextPHP Rest package, you need to add it to your project using Composer.
```bash
composer require nextphp/rest
```
# Example Project using NextPHP Rest
This is an example project demonstrating the usage of the NextPHP Rest package, which includes routing and HTTP handling capabilities.
Basic Usage
Defining Routes
Define routes using attributes to map HTTP methods to controller actions.
## Usage
### Using Controller
```php
getHeaders()['Authorization'] ?? '';
if (!$authHeader) {
return $response->withStatus(401)->withJSON(['error' => 'Unauthorized']);
}
list($jwt) = sscanf($authHeader, 'Bearer %s');
if (!$jwt) {
return $response->withStatus(401)->withJSON(['error' => 'Unauthorized']);
}
try {
$decoded = JWT::decode($jwt, new Key('your-secret-key', 'HS256'));
// Token is valid, proceed with the request
return $next($request, $response);
} catch (\Exception $e) {
return $response->withStatus(401)->withJSON(['error' => 'Unauthorized']);
}
}
}
```
### Service Layer Example
Services provide business logic and interact with repositories.
```php
userRepository = $userRepository;
}
#[Transactional]
public function registerUser(array $userData): User
{
$user = new User();
$user->name = $userData['name'];
$user->email = $userData['email'];
$user->password = password_hash($userData['password'], PASSWORD_DEFAULT);
$userArray = [
'name' => $user->name,
'email' => $user->email,
'password' => $user->password,
];
$this->userRepository->save($userArray);
return $user;
}
public function getAllUsers(): array
{
return $this->userRepository->findAll();
}
public function getUserById(int $id): ?User
{
$userArray = $this->userRepository->find($id);
if (!$userArray) {
return null;
}
$user = new User();
$user->id = $userArray['id'];
$user->name = $userArray['name'];
$user->email = $userArray['email'];
$user->password = $userArray['password'] ?? '';
return $user;
}
public function updateUser(int $id, array $data): ?User
{
$user = $this->getUserById($id);
if (!$user) {
return null;
}
foreach ($data as $key => $value) {
if (property_exists($user, $key)) {
$user->$key = $value;
}
}
$userArray = get_object_vars($user);
$this->userRepository->update($id, $userArray);
return $user;
}
public function deleteUser(int $id): bool
{
$user = $this->getUserById($id);
if (!$user) {
return false;
}
$this->userRepository->delete($id);
return true;
}
}
```
### Example Project
Example for your Project Structure
```code
example/
├── src/
│ ├── Entity/User.php
│ ├── Repository/UserRepository.php
│ ├── Service/UserService.php
│ ├── Resource/UserResource.php
├── example.php
├── composer.json
└── README.md
```
### Example or example.php
To use the NextPHP Rest package, you can create an index.php file and use the router to handle various HTTP requests. Here is an example of how you can do this:
Example index.php
```php
'/nextphp-beta',
'allowedOrigins' => [
'http://allowed-origin.com' => ['GET', 'POST'],
'http://another-allowed-origin.com' => ['GET', 'PUT'],
'*' => ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD', 'TRACE', 'CONNECT', 'PRI']
]
], $container);
// DI
$router->registerRoutesFromController(UserResource::class);
$router->registerRoutesFromController(PostResource::class);
$uri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
$request = new Request($method, $uri, getallheaders(), file_get_contents('php://input'), $_GET, $_POST);
$response = new Response();
$response = $router->dispatch($request, $response);
if ($response) {
http_response_code($response->getStatusCode());
foreach ($response->getHeaders() as $name => $value) {
header("$name: $value");
}
echo $response->getBody();
} else {
http_response_code(500);
echo json_encode(['error' => 'Internal Server Error', 'message' => 'No response returned.']);
}
```
## Contributing
We welcome contributions! Here’s how you can help:
- **Report Issues:** Found a bug? Report it on GitHub.
- **Suggest Features:** Have an idea? Share it with us.
- **Submit Pull Requests:** Improve the codebase.
- **Enhance Documentation:** Help us improve our docs.
For more details, see our [Contribution Guidelines](Contributing.md).
## Resources
- [Official Website](https://nextphp.io)
- [GitHub Repository](https://github.com/nextphp-projects/nextphp)
- [Documentation](https://github.com/nextphp-projects/nextphp)
## Join Our Community
- **Twitter:** Follow us on [Twitter](https://twitter.com/NextPHPOfficial)
- **Discord:** Join our [Discord](https://discord.gg/nextphp) community.
## Contact Us
- **Email:** support@nextphp.io
- **Forum:** [NextPHP Mastodon](https://mastodon.social/@nextphp)
- **GitHub Issues:** [NextPHP GitHub](https://github.com/nextphp-projects/nextphp/issues)
Thank you for being part of the NextPHP community!
### FAQ
### Q: How do I define a route?
A: Use the #[Get], #[Post], #[Put], #[Delete], #[Patch], etc. attributes to define a method as a route handler. Use #[RouteGroup] to define a common prefix for a group of routes.
For more details, see our FAQ.