Home Backend Development PHP Tutorial The use of action classes in Laravel programming architecture design

The use of action classes in Laravel programming architecture design

Jun 08, 2018 am 09:08 AM
laravel Architecture

This article mainly introduces you to the relevant information about the use of action classes in Laravel program architecture design ideas. The article introduces it in detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s learn together with the editor

Preface

When we talk about the architecture of applications, we often ask Come to a classic question, that is "Where should this code be placed?" Because Laravel is a fairly flexible framework, it's not that easy to answer this question. Should I write my business logic in the Model layer, the Controller layer, or somewhere else?

When your application has only one access point, it is okay to write business logic in the Controller layer. But now a more common situation is that there are many access points to call the same function module.

For example, many applications have the function of user registration. The process is to call a controller and then return a view indicating whether the registration is successful or failed. If this application also has a mobile version, it is likely to provide a set of APIs for mobile user registration, because the data format it needs to return is JSON. And it is also very common to use Laravel's artisan command to create users, especially in the early development stage of the project.

The above two pieces of code may not seem to have any problems, but as the business logic increases, the code will appear to be very redundant. For example, if you need to add the function of sending email notifications to users after new users register, you must add the code to send emails to both controllers above. But if we want to keep the code simple and elegant, we can write these business logic elsewhere.

Regarding the question of "where to write the business logic code", you can get a common answer in any forum, which is "use a service layer, and then call this service class in the controller layer". Yes, that’s right, the question is how should we design the service class? Is it to create a UserService class to implement all business logic related to the user, and then inject this class into the Controller layer that needs to be used? Or are there other options?

Avoid the Pitfall of Divine Classes

First, you can try to create a single class for a specific model that contains all the code. For example:

Looks perfect: we can declare or use create/delete methods in any controller and get the results we want. But what's wrong with this implementation? That is, we rarely use a single model in the process of solving problems.

For example, when we create an account for a user, we must also create a separate blog for the user at the same time. If we implement this process the current way, we have to create a BlogService class and then inject its dependencies into the UserService class.

Obviously, as the application business grows, there will be dozens to hundreds of service classes, some of which need to rely on 5 to 6 other service classes. service class, the final result is code redundancy and chaos, and this is a situation we want to avoid at all costs.

Introducing the single action class

So, if instead of using a single service class with several methods, we decided to divide it into several A category? The following is the method I have used in every recent project. The results are very good and I recommend it to everyone.

First, let's ditch the overly general and vague service terminology and take a look at our new action classes and define what they are and what they can do.

  • An action class should have a name that describes its function, such as: CreateOrder, ConfirmCheckout, DeleteProduct, AddProductToCart, etc.

  • It should have and only one public method as an API. Ideally, it should be the same method name, like handle() or execute() . This is very convenient if we need to implement some kind of adapter pattern for our action classes.

  • It must be request and response agnostic. It does not handle requests and does not send responses. Such responsibility should be assumed by the controller.

  • It can depend on other action classes.

  • If anything prevents it from executing and/or returning the expected value, then it must force the relevant business logic by throwing an Exception and let the caller (or Laravel ExceptionHandler ) to take responsibility for how to present/respond to exceptions.

Create our CreateUser action class

Now, let's take the previous example and refactor it with a single action class, which we will name CreateUser .

#You may wonder why this method throws an exception when the email address is already occupied. Isn’t this guaranteed by requesting verification? sure. However, wouldn't it be better to execute the business logic inside the action class? This makes the logic easier to understand and debug.

Let's look at the controller code after using our action class, as follows:


Now, no matter what changes we make, the user registers The process will be handled by API and Web versions, elegant and clean.

Nesting of action classes

Suppose we need an action class to import 1000 users into our application. We could write an action class and continue using the CreateUser class from above:


Pretty neat, isn't it? We can reuse the CreateUser code by embedding it in the Collection::map() method, which then returns a collection of all newly created users. When the email is occupied, we can return Null Object or record it in the Log file. You should have already thought of it.

Decoration of action classes

Now, suppose we want to record every newly registered user in the log. We can write the code inside the action class or use the decorator pattern.

We can then use Laravel's IoC container to bind the LogCreateUser class to the CreateUser class, so that whenever we need an instance of the latter, the former will be injected:

AppServiceProvider.php

This makes it more convenient to use configuration or environment variables to control the activation or deactivation of logging functionality:


AppServiceProvider.php

Summary

Using this method seems to require a lot of classes . Of course, user registration is just a simple example, designed to keep the code short and clear. Once the complexity of the project starts to grow, the real value of action classes becomes more and more obvious, because you clearly know where the code is and its boundaries.

Benefits of using single-action classes:

  • A small and single logical domain can prevent code duplication and improve code reusability and maintain stability.

  • Easy to conduct independent testing for various scenarios.

  • Meaningful names are easier to read in large projects.

  • Easy to decorate.

  • Consistency throughout the project: Prevent code from being distributed among Controllers, Models, etc.

Of course, this method is based on some of my experience using Laravel in the past few years and my practice in some projects. This worked really well for me and now I even use it on some small to medium projects.

If you have a different approach, I'd very much look forward to reading it.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Laravel framework implements the use of middleware for operation logging function

Laravel framework implements the use of listeners Perform sql statement recording function

The above is the detailed content of The use of action classes in Laravel programming architecture design. 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...

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 - Action URL Laravel - Action URL Aug 27, 2024 am 10:51 AM

Laravel - Action URL - Laravel 5.7 introduces a new feature called “callable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directl

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