How to use the Hyperf framework for API interface development
Environment setup
First, we need to set up the development environment of the Hyperf framework in the local environment. You can use the Composer tool to create a Hyperf project by running the following command in the terminal:
composer create-project hyperf/hyperf hyperf-demo
Create API Controller
In the Hyperf framework, we can define it by creating a controller API interface. In the terminal, switch to the project root directory and execute the following command to create an API controller:
php bin/hyperf.php make:controller User
This will create an API named UserController# in the
App/Controller directory ## controller file.
In the
UserController controller file, we can define multiple methods to handle different API interfaces. For example, we can define a method named
getUser to obtain user information. The code example of the method is as follows:
<?php declare(strict_types=1); namespace AppController; use HyperfHttpServerAnnotationController; use HyperfHttpServerAnnotationGetMapping; /** * @Controller(prefix="/user") */ class UserController { /** * @GetMapping(path="get") */ public function getUser(): array { return [ 'id' => 1, 'name' => 'John Doe', 'email' => 'john.doe@example.com', ]; } }
Controller and
GetMapping annotations to identify the controller and method.
GetMapping Annotations define the request method and path of the API interface.
In the terminal, switch to the project root directory and execute the following command to start the Hyperf service:
php bin/hyperf.php start
http://127.0.0.1:9501.
Address to obtain user information.
getUser method:
<?php declare(strict_types=1); namespace AppController; use HyperfHttpServerAnnotationController; use HyperfHttpServerAnnotationGetMapping; use AppRequestUserRequest; use HyperfDiAnnotationInject; use HyperfValidationContractValidatorFactoryInterface; /** * @Controller(prefix="/user") */ class UserController { /** * @Inject * @var ValidatorFactoryInterface */ protected $validationFactory; /** * @GetMapping(path="get") */ public function getUser(UserRequest $request): array { $validator = $this->validationFactory->make($request->all(), $request->rules()); if ($validator->fails()) { throw new InvalidArgumentException($validator->errors()->first()); } return [ 'id' => 1, 'name' => 'John Doe', 'email' => 'john.doe@example.com', ]; } }
UserRequest class to define validation rules for user request parameters. Obtain the
ValidatorFactoryInterface interface through dependency injection, and use its
make method to create a validator. If validation fails, we throw an
InvalidArgumentException exception.
The above is the detailed content of How to use the Hyperf framework for API interface development. For more information, please follow other related articles on the PHP Chinese website!