在 Laravel 中编写简洁的代码的策略
In this thread I’ll list tactics you can use to write cleaner code in Laravel. As you use them repeatedly, you’ll develop a sense for what’s good code and what’s bad code. I’ll also sprinkle some general Laravel code advice in between these tactics.
在本主题中,我将列出可用于在 Laravel 中编写更简洁代码的策略。 当您反复使用它们时,您将对什么是好的代码和什么是坏的代码产生一种感觉。 我还将在这些策略之间添加一些通用的 Laravel 代码建议。
It’s about the micro.
Using some “macro” philosophy for structuring your code, like hexagonal architecture or DDD won’t save you.
A clean codebase is the result of constant good decisions at the micro level.
这是关于 micro。
使用一些 micro
哲学来构建你的代码,比如使用六边形架构或 DDD 不会拯救你。
干净的代码库是微观层面不断做出正确决策的结果。
文章将在评论中持续更新,部分未翻译,有时间处理。
本作品采用《CC 协议》,转载必须注明作者和本文链接
不要编写重复的
else if
语句,而是使用数组根据您拥有的键查找所需的值。代码将更清晰且更具可读性,如果出现问题,您将看到可以理解的异常。 没有半途而废的边缘情况。
通过尽早返回值来避免不必要的嵌套
过多的嵌套与
else
语句往往会使代码更难阅读不要随机的拆开行,也不要让它们(一行代码)过长。
用
[
打开数组并缩进值往往效果很好。与长函数参数值相同。其他拆开行的好地方是链式调用和闭包
当可以直接传递值时,不要创建变量。
在可以提高可读性时创建变量
这与上一个提示相反。有时该值来自一个复杂的调用,因此,创建一个变量可以提高可读性并消除对注释的需要。
请记住上下文很重要,您的最终目标是可读性。
为业务逻辑创建模型方法
控制器应该很简单,它们应该说 “为订单创建发票” 之类的东西。它们不应该关心数据库的结构细节。
把它留给模型。
创建动作类
让我们扩展前面的例子。有时,为单个操作创建一个类可以清除一些事情。
模型应该封装与其相关的业务逻辑,但不能太大。
考虑使用表单请求。
它们时隐藏复杂验证逻辑的好方法。
但要小心 – 隐藏东西。当您的验证逻辑很简单时,在控制器中执行它没有任何问题,但其移至表单请求使其不那么明确。
使用事件。
考虑将一些逻辑从控制器卸载到事件。例如在创建模型时。
好处是创建这些模型在任何地方(控制器、作业等)都一样工作,并且控制器不必担心 DB 模型的细节。
提取方法。
如果某个方法太长或太复杂,并且很难理解到底发生了什么,请将逻辑拆分成多个方法。
创建辅助函数。
如果您经常重复某些代码,请考虑将其提取到辅助函数中是否会使代码更简洁。
避免助手类
有时,人们会将助手方法放在一个类中。
当心,它可能变得凌乱。这是一个只有静态方法用于辅助函数的类。通常最好将这些方法放入具有相关逻辑的类中,或者将它们保留为全局函数。
:bulb:用一个周末来学习正确的 OOP。
了解 静态、实例方法和变量与私有、受保护的、公开可见性之间的区别。还可以了解 Laravel 如何使用魔术方法。
作为初学者,您不需要它,但随着代码的增长,它至关重要。
不要只在类中编写过程代码。
这将之前的推文与此处的其他提示联系起来。OOP 的存在是为了是您的代码更具有可读性,请使用它。不要在控制器中编写 400 行长的程序代码。
这是我第一个 Laravel 项目的代码。
:bulb:
阅读诸如 SRP 之类的内容并在 合理 的范围内遵循它们
避免让类处理需要不相关的事情
但是,看在上帝的份上,不要为每一件事都创建一个类。您正在尝试编写干净的代码。您不是想取悦上帝。
:bulb:
当您可能到具有大量参数的函数时,它可能意味着:
以下是修复第二种情况的两种策略。
使用自定义集合。
创建自定义集合是实现更具表现力的语法的好方法。 考虑这个带有订单总数的例子。
不要使用缩写。
不要认为长变量/方法名称是错误的。 他们不是。 他们富有表现力。
最好调用较长的方法而不是较短的方法并检查文档块以了解它的作用
与变量相同。 不要使用无意义的 3 个字母缩写
为方法使用富有表现力的名称。
与其思考“这个对象能做什么”,不如想想“这个对象能做什么”。 例外情况适用,例如操作类,但这是一个很好的经验法则。
创建一次性特征
向它们所属的类添加方法比为所有内容创建操作类更干净,但它会使类变大
考虑使用特征。 它们主要用于代码重用,但一次性使用特征并没有错
创建一次性
Blade
包括。Similar to single-use traits.
类似于一次性特征。
当您有一个很长的模板并且希望使其更易于管理时,这种策略非常有用。
这没有什么问题
@including
Import namespaces instead of using aliases
Sometimes you may have multiple classes with the same name. Rather than importing them with an alias, import the namespaces.
Create query scopes for complex where()s.
Rather than writing complex where() clauses, create query scopes with expressive names.
This will make your e.g. controllers have to know less about the database structure and your code will be cleaner.
Don’t use model methods to retrieve data
If you want to retrieve some data from a model, create an accessor.
Keep methods for things that change the model in some way.
Use custom config files.
You can store things like “results per page” in config files. Don’t add them to the app config file though. Create your own. In my e-commerce project, I use config/shop.php.
Don't use a controller namespace
Instead of writing controller actions like PostController@index, use the callable array syntax [PostController::class, 'index'].
You will be able to navigate to the class by clicking PostController.
Consider single-action controllers
If you have a complex route action, consider moving it to a separate controller.
For OrderController::create, you'd create CreateOrderController.
Another solution is to move that logic to an action class — do what works best in your case.
:bulb:
Be friends with your IDE.
Install extensions, write annotations, use typehints. Your IDE will help you with getting your code working correctly, which lets you spend more energy on writing code that's also readable.
Use short operators.
PHP has many great operators that can replace ugly if checks. Memorize them.
:bulb:
Decide if you like spaces around operators.
Above you can see that I use space between ! and the value I'm negating. I like this, because it makes it clear that the value is being negated. I do the same around dots.
Decide if you like it. It can (imo) clean up your code.
Consider using helpers instead of facades. They can clean things up.
This is largely a matter of personal preference, but calling a global function instead of having to import a class and statically call a method feels nicer to me.
Bonus points for session('key') syntax.
Create custom Blade directives for business logic.
You can make your Blade templates more expressive by creating custom directives. For example, rather than checking if the user has the admin role, you could use @admin
Avoid queries in Blade when possible
Sometimes you may want to execute DB queries in blade. There are some ok use cases for this, such as in layout files.
But if it's a view returned by a controller, pass the data in the view data instead.
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
Use docblocks only when they clarify things.
Many people will disagree with this, because they do it. But it makes no sense.
There's no point in using docblocks when they don't give any extra information. If the typehint is enough, don't add a docblock.
That's just noise.
Have a single source of truth for validation rules.
If you validate some resource's attributes on multiple places, you definitely want to centralize these validation rules, so that you don't change them in one place but forget about the other places.
Use collections when they can clean up your code.
Don't turn all arrays into collections just because Laravel offers them, but DO turn arrays into collections when you can make use of collection syntax to clean up your code.
Write functional code when it benefits you.
Functional code can both clean things up and make them impossible to understand. Refactor common loops into functional calls, but don't write stupidly complex reduce()s just to avoid writing a loop. There's a use case for both.
Comments usually indicate poor code design.
Before writing a comment, ask yourself if you could rename some things or create variables to improve readability. If that's not possible, write the comment in a way that both your colleagues and you will understand in 6 months.
:bulb:
Context matters.
Above I said that moving business logic to action/service classes is good. But context matters
Here's code design advice from a popular "Laravel best practices" repo. There's absolutely no reason to put a 3-line check into a class. That's just overengineered
:bulb:
Use only what helps you and ignore everything else.
Your goal to write more readable code.
Your goal is NOT to do what someone said on the internet
These tips are just tactics that tend to help with clean code. Keep your end goal in mind and ask yourself "is this better?"
参考:翻译:Laravel 代码简洁之道(Clean Code)
楼主,你是百度贴吧过来的吗
楼主 为什么要把内容一段一段写到评论里 :joy: