在 Laravel 中编写简洁的代码的策略

文章翻译自 twitter.com/samuelstancl/status/12...

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 协议》,转载必须注明作者和本文链接
本帖由系统于 2年前 自动加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 59

Instead of writing repetitive else if statements, use an array to look up the wanted value based on the key you have.

不要编写重复的 else if 语句,而是使用数组根据您拥有的键查找所需的值。

The code will be cleaner & more readable and you will see understandable exceptions if something goes wrong. No half-passing edge cases.

代码将更清晰且更具可读性,如果出现问题,您将看到可以理解的异常。 没有半途而废的边缘情况。

2年前 评论

Try to avoid unnecessary nesting by returning a value early.

通过尽早返回值来避免不必要的嵌套

Too much nesting & else statements tend to make code harder to read.

过多的嵌套与 else 语句往往会使代码更难阅读

2年前 评论
坐忘 2年前

Don't split lines at random places, but don't make them too long either.

不要随机的拆开行,也不要让它们(一行代码)过长。

Opening an array with [ and indenting the values tends to work well. Same with long function parameter values.

[ 打开数组并缩进值往往效果很好。与长函数参数值相同。

Other good places to split lines are chained calls and closures.

其他拆开行的好地方是链式调用和闭包

file

2年前 评论

Don’t create variables when you can just pass the value directly.

当可以直接传递值时,不要创建变量。

file

2年前 评论

Create variables when they improve readability

在可以提高可读性时创建变量

The opposite of the previous tip. Sometimes the value comes from a complex call and as such, creating a variable improves readability & removes the need for a comment.

这与上一个提示相反。有时该值来自一个复杂的调用,因此,创建一个变量可以提高可读性并消除对注释的需要。

Remember that context matters & your end goal is readability

请记住上下文很重要,您的最终目标是可读性。

file

2年前 评论

Create model methods for business logic

为业务逻辑创建模型方法

Your controllers should be simple. They should say things like “create invoice for order”. They shouldn’t be concerned with the details of how your database is structured.

控制器应该很简单,它们应该说 “为订单创建发票” 之类的东西。它们不应该关心数据库的结构细节。

Leave that to the model.

把它留给模型。

file

2年前 评论

Create action classes

创建动作类

Let’s expand on the previous example. Sometimes, creating a class for a single action can clean things up.

让我们扩展前面的例子。有时,为单个操作创建一个类可以清除一些事情。

Models should encapsulate the business logic related to them, but they shouldn’t be too big.

模型应该封装与其相关的业务逻辑,但不能太大。

Laravel

2年前 评论
DotO 2年前
hmingv (作者) (楼主) 2年前
jackmeng 2年前
reiz568569 2年前
wlm212 1年前

Consider using form requests.

考虑使用表单请求。

They’re a great place to hide complex validation logic.

它们时隐藏复杂验证逻辑的好方法。

But beware of exactly that — hiding things. When your validation logic is simple, there’s nothing wrong with doing it in the controller. Moving it to a form request makes it less explicit

但要小心 – 隐藏东西。当您的验证逻辑很简单时,在控制器中执行它没有任何问题,但其移至表单请求使其不那么明确。

file

2年前 评论

Use events.

使用事件。

Consider offloading some logic from controllers to events. For example, when creating models.

考虑将一些逻辑从控制器卸载到事件。例如在创建模型时。

The benefit is that creating these models will work the same everywhere (controllers, jobs, …) and the controller has one less worry about the details of the DB schema

好处是创建这些模型在任何地方(控制器、作业等)都一样工作,并且控制器不必担心 DB 模型的细节。

Laravel

2年前 评论
jackmeng 2年前
DotO 2年前

Extract methods.

提取方法。

If some method is too long or complex, and it's hard to understand what exactly is happening, split the logic into multiple methods.

如果某个方法太长或太复杂,并且很难理解到底发生了什么,请将逻辑拆分成多个方法。

file

2年前 评论

Create helper functions.

创建辅助函数。

If you repeat some code a lot, consider if extracting it to a helper function would make the code cleaner.

如果您经常重复某些代码,请考虑将其提取到辅助函数中是否会使代码更简洁。

file

2年前 评论

Avoid helper classes.

避免助手类

Sometimes people put helpers into a class.

有时,人们会将助手方法放在一个类中。

Beware, it can get messy. This is a class with only static methods used as helper functions. It's usually better to put these methods into classes with related logic or just keep them as global functions.

当心,它可能变得凌乱。这是一个只有静态方法用于辅助函数的类。通常最好将这些方法放入具有相关逻辑的类中,或者将它们保留为全局函数。

file

2年前 评论

:bulb:Dedicate a weekend towards learning proper OOP.

:bulb:用一个周末来学习正确的 OOP。

Know the difference between static/instance methods & variables and private/protected/public visibility. Also learn how Laravel uses magic methods.

了解 静态、实例方法和变量与私有、受保护的、公开可见性之间的区别。还可以了解 Laravel 如何使用魔术方法。

You don't need this as a beginner, but as your code grows, it's crucial.

作为初学者,您不需要它,但随着代码的增长,它至关重要。

2年前 评论

Don't just write procedural code in classes.

不要只在类中编写过程代码。

This ties the previous tweet with the other tips here. OOP exists to make your code more readable, use it. Don't just write 400 line long procedural code in controller actions.

这将之前的推文与此处的其他提示联系起来。OOP 的存在是为了是您的代码更具有可读性,请使用它。不要在控制器中编写 400 行长的程序代码。

Here's code from my first Laravel project

这是我第一个 Laravel 项目的代码。

file

2年前 评论

:bulb:

Read up on things like SRP & follow them to reasonable extent

阅读诸如 SRP 之类的内容并在 合理 的范围内遵循它们

Avoid having classes that deal with many unrelated things

避免让类处理需要不相关的事情

But, for the love of god, don't create a class for every single thing. You're trying to write clean code. You're not trying to please the separation gods

但是,看在上帝的份上,不要为每一件事都创建一个类。您正在尝试编写干净的代码。您不是想取悦上帝。

2年前 评论

:bulb:

When you see a function with a huge amount of parameters, it can mean:

当您可能到具有大量参数的函数时,它可能意味着:

  1. The function has too many responsibilities. Separate.
  2. The responsibilities are fine, but you should refactor the long signature.
  1. 函数的指责过多,分离。
  2. 指责没问题,但您应该重构长签名。

Below are two tactics for the fixing second case.

以下是修复第二种情况的两种策略。

2年前 评论
hmingv (作者) (楼主) 2年前
hmingv (作者) (楼主) 2年前
reiz568569 2年前

Use custom collections.

使用自定义集合。

Creating custom collections can be a great way to achieve more expressive syntax. Consider this example with order totals.

创建自定义集合是实现更具表现力的语法的好方法。 考虑这个带有订单总数的例子。

file

2年前 评论

Don't use abbreviations.

不要使用缩写。

Don't think that long variable/method names are wrong. They're not. They're expressive.

不要认为长变量/方法名称是错误的。 他们不是。 他们富有表现力。

Better to call a longer method than a short one and check the docblock to understand what it does

最好调用较长的方法而不是较短的方法并检查文档块以了解它的作用

Same with variables. Don't use nonsense 3-letters abbreviations

与变量相同。 不要使用无意义的 3 个字母缩写

file

2年前 评论

Use expressive names for methods.

为方法使用富有表现力的名称。

Rather than thinking “what can this object do”, think about “what can be done with this object”. Exceptions apply, such as with action classes, but this is a good rule of thumb.

与其思考“这个对象能做什么”,不如想想“这个对象能做什么”。 例外情况适用,例如操作类,但这是一个很好的经验法则。

file

2年前 评论

Create single-use traits

创建一次性特征

Adding methods to classes where they belong is cleaner than creating action classes for everything, but it can make the classes grow big

向它们所属的类添加方法比为所有内容创建操作类更干净,但它会使类变大

Consider using traits. They're meant primarily for code reuse, but there's nothing wrong with single-use traits

考虑使用特征。 它们主要用于代码重用,但一次性使用特征并没有错

file

2年前 评论

Create single-use Blade includes.

创建一次性Blade包括。

Similar to single-use traits.

类似于一次性特征。

This tactic is great when you have a very long template and you want to make it more manageable.

当您有一个很长的模板并且希望使其更易于管理时,这种策略非常有用。

There's nothing wrong with

这没有什么问题

@including

@including

headers and footers in layouts, or things like complex forms in page views. 布局中的页眉和页脚,或页面视图中的复杂表单等内容。

2年前 评论

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.

file

2年前 评论

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.

file

2年前 评论

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.

file

2年前 评论

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.

file

2年前 评论

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.

file

2年前 评论

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.

file

file

2年前 评论

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

file

2年前 评论

Use short operators.

PHP has many great operators that can replace ugly if checks. Memorize them.

file

2年前 评论

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

2年前 评论

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.

file

2年前 评论

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

file

2年前 评论

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.

file

2年前 评论

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

file

2年前 评论

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.

file

2年前 评论

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.

2年前 评论
hmingv (作者) (楼主) 2年前

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.

file

2年前 评论

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.

file

2年前 评论

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.

2年前 评论

: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

file

2年前 评论

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

2年前 评论

楼主,你是百度贴吧过来的吗

2年前 评论
看上隔壁小花了啦 2年前
徐小花 (作者) 2年前
飞飞鱼 2年前

楼主 为什么要把内容一段一段写到评论里 :joy:

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!