


The use of action classes in Laravel programming architecture design
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools