Home  >  Article  >  Backend Development  >  The use of action classes in Laravel programming architecture design

The use of action classes in Laravel programming architecture design

不言
不言Original
2018-06-08 09:08:141902browse

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:
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