Laravel Clean Code (3)
In the previous parts of clean coding in Laravel, we learned about 10 interesting tips for writing clean and readable code. In this third, we will share the third point with you. Do not forget that these items are in no order or priority and each can be important in its place.
11. Creating model methods for business logic
Your controllers should be simple. They should say things like “Create invoice for order”. They don’t have to worry about the details of your database structure. Leave it to the model.
12. Using events
Move some logic from controllers to events. For example, the advantage when creating models is that creating these models works the same way everywhere (controllers, jobs, etc.) and the controller has less to worry about the details of the database schema.
13. Follow naming rules
The name of the controller must start with a noun (singular) followed by the word “Controller”.
The name of the models should be singular and the first letter should be capitalized.
The names of the migration files must follow the following patterns:
The name of model properties should be snake_case.
Table column names should be snake_case without model name.
The hasOne or belongsTo relation methods must be singular.
Methods must be camelCase.
Paths must be in the plural form of the resource to be manipulated and all must be in lower-case.
14. Removing Flag Argument
Flag Argument is an argument that is usually passed to a function in the form of Boolean, and its presence or absence causes the function to show different behaviors, which violates the first principle of SOLID, which says that a function should only do one thing.
- In the picture, the first function takes a Flag Argument called silentMode, which makes the function do 2 things
- Mr. Robert C. Martin says that this work is not considered a clean coding and it is better to convert the function into several functions, each of which is responsible for a specific and predictable behavior.
15. Use strict comparison
Always use strict comparison (=== and !==). If needed, cast things go the correct type before comparing. Better than weird == results
Also consider enabling strict types in your code. This will prevent passing variables of wrong data types to functions