Home > PHP Framework > Laravel > Detailed introduction to the writing steps and practices of Laravel Action

Detailed introduction to the writing steps and practices of Laravel Action

PHPz
Release: 2023-04-21 11:18:26
Original
814 people have browsed it

Laravel is a very popular PHP development framework, which is popular for its simple and powerful API and comprehensive toolkit. In Laravel, "Actions" are a concept that allows you to build controllers and simplify your logic layer more easily. The following is a detailed introduction to the steps and practices on how to write Laravel Action.

  1. Create Action Class

First, you need to create an Action class. In Laravel 8 and above, you can create it through the Artisan command:

php artisan make:action MyAction
Copy after login

This will create a new class file "MyAction.php" for you in the app/Action directory. Now, we can start writing the logic of the Action.

  1. Writing the logic of Action

In your Action, you can define specific business logic for each method in the controller. Here we will create a method to handle the logic of user login.

<?php

namespace App\Actions;

use Illuminate\Support\Facades\Auth;

class LoginUserAction
{
    public function execute(array $credentials)
    {
        $attempt = Auth::attempt($credentials);

        if (!$attempt) {
            throw new \Exception(&#39;Invalid login credentials&#39;);
        }

        return Auth::user();
    }
}
Copy after login

In the above example, we created an Action named LoginUserAction. It receives an array containing the user's login credentials, performs a login attempt, and throws an exception if there is an error, otherwise it returns the successfully authenticated user.

It is worth noting that we use Laravel's Auth facade to perform login operations. This allows us to easily leverage Laravel's authentication system.

  1. Using Action in Controller

Now, we have created an Action class and defined its logic. The next step is to use it in the controller.

The first step to using Action is to open the controller and add a use statement to introduce the Action class:

<?php

namespace App\Http\Controllers;

use App\Actions\LoginUserAction;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login(Request $request, LoginUserAction $loginAction)
    {
        $credentials = $request->only(['email', 'password']);

        try {
            $user = $loginAction->execute($credentials);
        } catch (\Exception $e) {
            return response()->json([
                'message' => $e->getMessage()
            ], 401);
        }

        return response()->json(compact('user'));
    }
}
Copy after login

In the above code, we referenced LoginUserAction from our own namespace . Then we added the login() method, whose first parameter is Laravel's Request object and whose second parameter is the LoginUserAction instance we created above.

In login(), we first extract the email and password based on the request content, and then call our Action to execute the logic through the $credentials parameters. If successful, we return the user in JSON format, otherwise we return an error message to the client.

  1. Call Action

Now we can access our login() method and call the execute method in the LoginUserAction class. We will pass an array containing some login credentials in the HTTP request and return the result.

Define the corresponding login route in the route:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;

Route::post(&#39;/login&#39;, [AuthController::class, &#39;login&#39;])->name('login');
Copy after login

Now we can access the /login route of our laravel application, which will look like this:

POST /login HTTP/1.1
Host: localhost:8000
Content-Type: application/json

{
    "email": "user@example.com",
    "password": "my_password"
}
Copy after login

This will trigger our The login() method defined in the controller calls LoginUserAction and passes in email and password as parameters.

  1. Summary

Laravel Action provides a simple, clean way to organize your business logic. By moving business logic out of the controller and into Action classes, you can achieve a lot of code reuse and maintainability improvements.

When using Laravel Action, you should follow the following two best practices:

  • Each method should try to do only one thing.
  • Avoid direct access to external classes or objects in the Action class, and use the method of passing variables to achieve common and repeated processing of data.

Finally, it should be noted that the Action function was introduced in Laravel 8. If you are using an older version of Laravel, you may need to manually create the Action class and store the class file in a appropriate location and then manually instantiate and call it in the controller.

The above is the detailed content of Detailed introduction to the writing steps and practices of Laravel Action. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template