Home Backend Development PHP Tutorial How to implement Laravel 5.5 reactive interface

How to implement Laravel 5.5 reactive interface

May 25, 2018 pm 03:27 PM
laravel response interface

Laravel is a simple and elegant PHP Web development framework (PHP Web Framework). It can free you from messy codes like noodles; it can help you build a perfect network APP, and every line of code can be concise and expressive.

Laravel 5.5 adds a new return type to routing: Responsable interface ). This interface allows objects to be automatically converted into a standard HTTP response interface when returned from a controller or closure route. Any object that implements the Responsable interface must implement a toResponse() method, which converts the object into an HTTP response object.

Look at the example:

use Illuminate\Contracts\Support\Responsable;
  
class ExampleObject implements Responsable
{
 public function __construct($name = null)
 {
  $this->name = $name ?? 'Teapot'; 
 }
  
 public function status()
 {
  switch(strtolower($this->name)) {
   case 'teapot':
    return 418;
   default:
    return 200;
  }
 }
  
 public function toResponse()
 {
  return response(
   "Hello {$this->name}",
   $this->status(),
   ['X-Person' => $this->name]
  );
 }
}
Copy after login

When using this ExampleObject in routing, you can do this:

Route::get('/hello', function() {
 return new ExampleObject(request('name'));
});
Copy after login

In the Laravel framework, the Route class can now prepare response content Check this type (implementing the Responsable interface):

if ($response instanceof Responsable) {
 $response = $response->toResponse();
}
Copy after login

If you use multiple response types to organize your response content under the App\Http\Responses namespace, you can refer to the following example. This sample demonstrates how to support Posts (Collection of multiple instances):

posts = $posts;
 }
  
 public function toResponse()
 {
  return response()->json($this->transformPosts());
 }
  
 protected function transformPosts()
 {
  return $this->posts->map(function ($post) {
   return [
    'title' => $post->title,
    'description' => $post->description,
    'body' => $post->body,
    'published_date' => $post->published_at->toIso8601String(),
    'created' => $post->created_at->toIso8601String(),
   ];
  });
 }
}
Copy after login

The above is just a basic example to simulate a simple application scenario: return a JSON response, but you hope that the response layer does not simply use the built-in implementation to convert the object to JSON ization, but to do some content processing. The above example also assumes App\Http\Responses\Response This class can provide some basic functions. Of course, the response layer can also contain some conversion code (similar to Fractal) instead of doing such conversion directly in the controller.

The controller code that cooperates with the PostIndexResponse class in the above example is similar to the following:

If you want to know more details about this interface, you can view the commit of the relevant code in the project.

The above content is a detailed explanation of the responsive interface provided in Laravel 5.5 for responding to requests. I hope it can help everyone.

Related recommendations:

Laravel5.5 new features error reporting and graphic introduction of the display

About friendly error reporting in Laravel5.5 Display and detailed explanation

Detailed introduction of Package Auto Discovery in Laravel5.5

The above is the detailed content of How to implement Laravel 5.5 reactive interface. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

What is the difference between an abstract class and an interface in PHP? What is the difference between an abstract class and an interface in PHP? Apr 08, 2025 am 12:08 AM

The main difference between an abstract class and an interface is that an abstract class can contain the implementation of a method, while an interface can only define the signature of a method. 1. Abstract class is defined using abstract keyword, which can contain abstract and concrete methods, suitable for providing default implementations and shared code. 2. The interface is defined using the interface keyword, which only contains method signatures, which is suitable for defining behavioral norms and multiple inheritance.

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

See all articles