充分记录您PHP代码

tech2023-10-12  97

介绍 (Introduction)

Pretty much every PHP developer writes comments along with the actual code. But the language itself doesn’t impose any rules on how to do so. You just have to wrap them around some specific tags and then you can write any content you want. So what exactly should be put in the comment blocks to keep them useful? Which parts of the code should be documented and which shouldn’t? In this article I will present some important rules which may help you in keeping your PHP code well documented and understandable.

几乎每个PHP开发人员都会在实际代码中写注释。 但是语言本身并没有对如何执行施加任何规则。 您只需要将它们包装在一些特定的标签周围,然后就可以编写所需的任何内容。 那么,应在注释块中确切放置什么以使其保持有用? 代码的哪些部分应该记录,哪些不应该记录? 在本文中,我将介绍一些重要的规则,这些规则可以帮助您保持PHP代码的文档化和可理解性。

1.编写自我解释的代码 (1. Write code that explains itself)

First and foremost, the code you write may serve as a good piece of documentation even without adding a single comment block to it. While transforming the logic into pieces of code you can do a lot to make the code clear. Here are just a few examples:

首先,即使没有在其中添加任何注释块,您编写的代码也可以作为很好的文档。 在将逻辑转换为代码段时,您可以做很多事情来使代码清晰。 这里只是几个例子:

Variable, function and class naming As you can name your pieces of code in almost any way you want, you can use it as your advantage in terms of keeping the code understandable. Just remember to choose clear names, not to make up any strange abbreviations or use names that may be ambiguous. If your variable represents an instance of a VeryImportantCustomer class, just call it $veryImportantCustomer, not $customer, $vimpCust or $tempcustomer. Don’t be afraid of making typos in longer names as your IDE will probably warn you about unused variables or other inconsistencies in your code. I’m sure that using proper naming will help a lot in figuring out what’s going on in your code. It’s a simple rule but it may be easily forgotten in your everyday work.

变量,函数和类的命名由于几乎可以用任何方式命名代码段,因此可以在使代码易于理解方面发挥其优势。 只需记住选择清晰的名称,而不要使用任何奇怪的缩写或使用可能含糊的名称。 如果您的变量表示VeryImportantCustomer类的实例,只需将其$veryImportantCustomer为$veryImportantCustomer ,而不是$customer , $vimpCust或$tempcustomer 。 不要担心使用较长的名称输入错误,因为您的IDE可能会警告您有关未使用的变量或代码中其他不一致的地方。 我确信使用正确的命名将有助于弄清楚代码中正在发生的事情。 这是一条简单的规则,但在您的日常工作中可能会轻易忘记。

Type hinting PHP allows you to put class/interface names or array / callable keywords next to a function parameter. It prevents you from making wrong function calls but it also serves as an important piece of information for anyone reading your code. You don’t have to examine the function body to get to know how to call the function. You can also quickly check how the different functions and classes can pass values between each other. And remember that your IDE will probably interpret the type hints and use them to describe the functions in popups or hints which are being displayed while you’re working.

类型提示 PHP 使您可以将类/接口名称或array / callable关键字放在函数参数旁边。 它可以防止您进行错误的函数调用,但对于任何阅读您的代码的人来说,它也是重要的信息。 您无需检查函数主体即可知道如何调用该函数。 您还可以快速检查不同的函数和类如何在彼此之间传递值。 请记住,您的IDE可能会解释类型提示,并使用它们来描述工作时正在显示的弹出窗口或提示中的函数。

Method visibility Another concept worth mentioning is the method visibility. Assigning proper visibility to class methods is said to be an important part of writing quality object-oriented code. On one hand, it shows which code represents the part of the logic that should stay inside the class and shouldn’t be revealed to other classes in the application. On the other, it exposes certain class methods to public access so they can be called from outside the class and communicate with other parts of the application.

方法可见性另一个值得一提的概念是方法可见性 。 为类方法分配适当的可见性据说是编写高质量的面向对象代码的重要部分。 一方面,它显示了哪些代码代表应该保留在类中并且不应向应用程序中的其他类透露的逻辑部分。 另一方面,它将某些类方法公开给公众访问,因此可以从类外部调用它们并与应用程序的其他部分进行通信。

If you write code that includes setting proper method visibility, other developers will quickly figure out how to work with the class you’ve developed. They will see that there are a few public methods that they can refer to in their code. They will also notice which parts of the logic that you wrote are left to be handled by private class methods and probably shouldn’t be touched.

如果您编写的代码包括设置适当的方法可见性,那么其他开发人员将Swift弄清楚如何使用已开发的类。 他们将看到在代码中可以引用一些公共方法。 他们还将注意到您编写的逻辑的哪些部分留待私有类方法处理,并且可能不应该涉及。

Again, such hints are also being interpreted by your IDE. The editor you use can probably show you a list of class methods, along with their visibility. Just look at the image below and notice the lock icons next to the method names:

同样,IDE也将解释此类提示。 您使用的编辑器可能会向您显示类方法的列表以及它们的可见性。 只需看下面的图片,您会注意到方法名称旁边的锁定图标:

2.保持平衡 (2. Keep the balance)

Of course you may feel that the code itself is not always clear enough and needs additional explanation. It is especially true when you’re implementing a complicated part of the business logic, performing complex calculations or just using commands that are difficult to understand at first sight (like regular expression patterns, array transformations etc.). In such cases writing a short comment will certainly help in getting to know what’s going on.

当然,您可能会觉得代码本身并不总是很清楚,需要其他说明。 当您实现业务逻辑的复杂部分,执行复杂的计算或仅使用乍一看很难理解的命令(例如正则表达式模式,数组转换等)时,尤其如此。 在这种情况下,写简短的评论肯定会帮助您了解正在发生的事情。

On the other hand, comment blocks shouldn’t make up for poorly written code. If your code contains too many loops or control structures and even you don’t know how it works without analyzing it for a couple of minutes, leaving it like that with a few comment lines isn’t the best solution. You should rather put some effort in refactoring the code instead of trying to explain it in comments.

另一方面,注释块不应弥补编写不良的代码。 如果您的代码包含过多的循环或控制结构,而您甚至不分析几分钟就不知道它是如何工作的,那么让它带有一些注释行并不是最好的解决方案。 您应该花一些精力来重构代码,而不要尝试在注释中进行解释。

Aside from complex code blocks, there are also such parts of code that are clear and do not represent any complicated logic. Some developers tend to put comment blocks even for these parts of their apps, which is unnecessary in my opinion. Let me show you an example:

除了复杂的代码块外,代码的这些部分也很清晰,不代表任何复杂的逻辑。 有些开发人员倾向于在其应用程序的这些部分都放置注释块,我认为这是不必要的。 让我给你看一个例子:

<?php class Deposit { /** * The deposit owner. * * @var string */ private $_owner; /** * The deposit amount. * * @var float */ private $_amount; /** * The date when the deposit was opened. * * @var DateTime */ private $_dateOpened; /** * Class constructor. * */ public function __construct() { //... } /** * Sets the deposit owner. * * @param string $owner The deposit owner name. */ public function setOwner($owner) { $this->_owner = $owner; } ?>

Remember that the person who reads your code is usually a developer (or at least I suppose so), so he/she will be able to figure out that the _owner property of the Deposit class represents a deposit owner. That’s why I think that putting additional comments to such parts of the code can even make it less readable instead of helping the reader in any way.

请记住,读取您的代码的人通常是开发人员(或者至少我想是这样),因此他/她将能够确定Deposit类的_owner属性表示存款所有者。 这就是为什么我认为在代码的这些部分加上额外的注释甚至会使它的可读性降低,而不是以任何方式帮助读者。

Comments are often also unnecessary in other simple parts of your code, not only in class property definitions or typical methods (like constructors, getters or setters). Just see the example below:

在代码的其他简单部分中,通常也不需要注释,不仅在类属性定义或典型方法(如构造函数,getter或setter)中。 请看下面的例子:

<?php public function showUserDetails() { $userId = $this->Session->read('userId'); $userData = $this->getUserData($userId); if(!$user->isActive()) { throw new Exception("The user account hasn't been activated."); } //... } ?>

I’m sure that you can easily figure out what’s going on in the part of the code presented above. But if you wanted to comment the code, it will probably look like this:

我相信您可以轻松地弄清楚上面显示的代码部分中发生了什么。 但是,如果您想注释代码,它可能看起来像这样:

<?php /** * Shows the details of the user that is currently * logged in. * */ public function showUserDetails() { //get the current user from session $userId = $this->Session->read('userId'); //load the user data from database $userData = $this->getUserData($userId); //check if the user has an active account if(!$user->isActive()) { throw new Exception("The user account hasn't been activated."); } //... } ?>

In fact, the comments added to the method contain almost the same words as those used in the code. Like we previously stated, proper naming makes your code understandable and easy to read. In my opinion, the method shown in the example above doesn’t need any additional comments as everything is described by the code itself. Of course, I still encourage you to write comments in those parts of your app that are more complex and need additional explanation.

实际上,添加到该方法的注释几乎包含与代码中使用的相同的词。 如我们先前所述,正确的命名使您的代码易于理解且易于阅读。 我认为,上面示例中显示的方法不需要任何其他注释,因为所有内容均由代码本身描述。 当然,我仍然鼓励您在应用程序中较复杂的部分并需要附加说明的地方写评论。

3.记住关于文档块 (3. Remember about the doc blocks)

As you can see in the code examples above, some comment blocks contain specific keywords beginning with the @ character. I used @var to describe the type of a class property and @param to inform about the method parameter type. You can also use @return tag which informs about the type of the value being returned by a function. Other tags may be employed to describe some general info about the application or its part (like the author, the package, the type of licence). You can read more about the doc blocks in the Introduction to PhpDoc article written by Moshe Teutsch.

如您在上面的代码示例中所看到的,某些注释块包含以@字符开头的特定关键字。 我使用@var来描述类属性的类型,并使用@param来告知方法参数的类型。 您也可以使用@return标记,该标记告知函数所返回的值的类型。 可以使用其他标签来描述有关应用程序或其部分的一些常规信息(例如作者,软件包,许可证的类型)。 您可以在Moshe Teutsch撰写的PhpDoc 简介文章中阅读有关doc块的更多信息。

Doc blocks tags contain information that cannot be included in the code itself. Specifying the type of class properties or function return values is especially helpful as it can be parsed by most of the IDEs and shown in hints. Of course you can also insert a custom text in a doc block which will serve as a function or class documentation. It may be especially important if your project needs to have its documentation available from outside the code. In such cases you can make use of the apps that analyze the doc blocks and generate the documentation of the whole application basing on their content. Read Bruno Skvorc’s Generate documentation with ApiGen article to find out more about such an approach.

Doc块标签包含无法包含在代码本身中的信息。 指定类属性或函数返回值的类型特别有用,因为大多数IDE都可以对其进行解析并显示在提示中。 当然,您也可以在doc块中插入自定义文本,以用作函数或类文档。 如果您的项目需要从代码外部获得其文档,则这一点尤其重要。 在这种情况下,您可以利用分析文档块的应用程序,并根据其内容生成整个应用程序的文档。 阅读Bruno Skvorc的“ 使用ApiGen生成文档”文章,以了解有关这种方法的更多信息。

If the code is easy to understand and I don’t need to produce an extended documentation, I just keep the tags that provide the information about the variable types and return values. In result, the code doesn’t get excessively complicated:

如果代码易于理解,而无需编写扩展文档,则只需保留提供变量类型和返回值信息的标签。 结果,代码不会变得过于复杂:

<?php class Deposit { /** * @var string */ private $_owner; /** * @var float */ private $_amount; /** * @var DateTime */ private $_dateOpened; //... /** * @param string $owner */ public function setOwner($owner) { $this->_owner = $owner; } ?>

摘要 (Summary)

In this article I presented some tips on how to maintain the code documentation in a PHP application. I think comments aren’t necessary if you produce code which is clear and just explains itself. The proper place to put comments is when you implement some complex logic or use commands that are just not very readable for a human. It is also worth remembering to insert doc block tags which describe variable types or function return values as such information cannot be included in the code itself. If you need to maintain more detailed project documentation, also put appropriate descriptions in doc blocks.

在本文中,我介绍了有关如何在PHP应用程序中维护代码文档的一些技巧。 我认为,如果您生成的代码清晰且能自我解释,则注释不是必需的。 进行注释的适当位置是当您实现一些复杂的逻辑或使用对于人类而言不太可读的命令时。 还应该记住插入描述变量类型或函数返回值的doc块标记,因为此类信息不能包含在代码本身中。 如果您需要维护更详细的项目文档,请在文档块中添加适当的描述。

Feel free to put your comments about the points presented in the article or contact me through Google+. If you have a different opinion or use different rules in your work, tell us about it!

请随意发表您对本文中提出的观点的评论,或通过Google+与我联系。 如果您有不同的意见或在工作中使用不同的规则,请告诉我们!

翻译自: https://www.sitepoint.com/keeping-php-code-well-documented/

相关资源:jdk-8u281-windows-x64.exe
最新回复(0)