PHP CodeSniffer 有多大用处?代码标准执行的一般情况?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/982333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How useful is PHP CodeSniffer? Code Standards Enforcement in General?
提问by Mike B
I'm dabbling with the idea of setting up PHP CodeSnifferon our continuous integration server in an effort to improve the quality of our code-base. After reading the documentation I'm very excited about the idea of normalizing and enforcing our coding standards. However, I'm left wondering about the actual improvement to our product. I'm well aware that the sniffer only detects violations to a defined coding-standard but what type of benefits does a clean, consistent, code-base provide? Is it worth the extra work to refactor a project with 100k+ lines of code to conform to the PEAR standard?
我正在尝试在我们的持续集成服务器上设置PHP CodeSniffer,以提高我们代码库的质量。阅读文档后,我对规范化和执行我们的编码标准的想法感到非常兴奋。但是,我对我们产品的实际改进感到疑惑。我很清楚嗅探器只检测违反定义的编码标准,但是干净、一致的代码库提供什么类型的好处?用 10 万多行代码重构一个项目以符合 PEAR 标准是否值得付出额外的努力?
For those who are not familiar with PHP CodeSniffer or code-smell in general, here is an example output:
对于那些不熟悉 PHP CodeSniffer 或一般代码气味的人,这里是一个示例输出:
FILE: /path/to/code/myfile.php
FOUND 5 ERROR(S) AFFECTING 2 LINE(S)
--
2 | ERROR | Missing file doc comment
20 | ERROR | PHP keywords must be lowercase; expected "false" but found "FALSE"
47 | ERROR | Line not indented correctly; expected 4 spaces but found 1
51 | ERROR | Missing function doc comment
88 | ERROR | Line not indented correctly; expected 9 spaces but found 6
文件:/path/to/code/myfile.php 发现
5 个错误影响 2 行
--
2 | 错误 | 缺少文件文档注释
20 | 错误 | PHP 关键字必须小写;预期为“假”但发现“假”
47 | 错误 | 行缩进不正确;预期 4 个空格,但发现 1
51 | 错误 | 缺少函数文档注释
88 | 错误 | 行缩进不正确;预计有 9 个空格,但发现了 6 个
Strictly speaking, the user/client would not notice any difference in a product that was refactored to be standards-compliant but I'm wondering if there are other hidden benefits
严格来说,用户/客户不会注意到重构为符合标准的产品有任何不同,但我想知道是否还有其他隐藏的好处
Right now our code is by no means sloppy and we try to follow our own personal standards which, for the most part, are derived from Pear's Coding Standardsbut a trained eye can spot the differences.
现在我们的代码绝不马虎,我们尝试遵循我们自己的个人标准,这些标准大部分源自Pear 的编码标准,但训练有素的眼睛可以发现差异。
So my question is how much do they improve the quality of a product. What kind of latent benefits resulted from it?
所以我的问题是他们在多大程度上提高了产品的质量。它带来了什么样的潜在好处?
Am I just being obsessive-compulsive with my desire to move our product closer to a set of standards? Would it be worth it? If so, What kind of strategy did you use to implement the code-sniffer and correct the subsequent violations that were detected?
我是否只是对让我们的产品更接近一组标准的渴望有强迫症?值得吗?如果是这样,您使用什么样的策略来实施代码嗅探器并纠正检测到的后续违规行为?
回答by Greg Sherwood
Firstly, I'm the maintainer of PHP_CodeSniffer, so I'm clearly biased in this area. But I've also worked on some big code bases in my 10 years as a PHP dev, so I hope I can bring some concrete reasons to why coding standards are a good thing. I could write a blog series on this topic, but I'll just give you a little story about how PHP_CodeSniffer came about so you can understand the problem that the tool solved for me.
首先,我是 PHP_CodeSniffer 的维护者,所以我显然对这个领域有偏见。但在我作为 PHP 开发人员的 10 年里,我也研究过一些大型代码库,所以我希望我能提供一些具体的理由来说明为什么编码标准是一件好事。我可以写一个关于这个主题的博客系列,但我只会给你讲一个关于 PHP_CodeSniffer 是如何产生的小故事,这样你就可以理解这个工具为我解决的问题。
I've worked on a few big CMS projects. The first had a heap of code behind it and a relatively small development team. We had no standards. But we had no real problems. The team was small and stayed together for quite a while. We got used to each other.
我从事过一些大型 CMS 项目。第一个背后有一堆代码和一个相对较小的开发团队。我们没有标准。但我们没有真正的问题。团队很小,在一起呆了很长时间。我们彼此都习惯了。
Then we built a new CMS. We started fresh with just a couple of devs. I was then part of a team of just two developers. Again, coding standards didn't cause us any issues. Me and the other dev came from the same background and had already established some guidelines that we followed. We didn't need PHPCS back then.
然后我们建立了一个新的CMS。我们从几个开发人员开始。当时我是一个只有两个开发人员的团队的一员。同样,编码标准没有给我们带来任何问题。我和另一个开发人员来自相同的背景,并且已经制定了一些我们遵循的指导方针。那时我们不需要 PHPCS。
But that team grew a developer at a time and eventually reached 12 full-time devs and quite a few came and went. Some came from the old CMS and some came from outside the company. All had different backgrounds and a different approach to development. It was obvious who wrote what code because the styles were so different. Whenever you worked on something complex, you'd first have to adjust to their style because it was just not the way you were used to seeing code. It's like reading Shakespeare for the first time. You need to get used to it before you can read at your natural pace.
但是那个团队一次培养了一个开发人员,最终达到了 12 名全职开发人员,而且来来去去的人也不少。有些来自旧的 CMS,有些来自公司外部。所有人都有不同的背景和不同的发展方法。很明显谁写了什么代码,因为风格是如此不同。每当你处理一些复杂的事情时,你首先必须适应他们的风格,因为这不是你习惯看到代码的方式。这就像第一次阅读莎士比亚。您需要习惯它,然后才能以自然的速度阅读。
For developers, that extra time to have to stop and figure out another coding style is just pure wasted time. It's a chance for an idea to slip away while you are bogged down with spacing, indentation and bracket position. At the end of the day, these things just don't matter. But let me tell you, they matter a lot if they are causing developers to break their flow. So we needed a way to make them get right out of the way and let developers do what they do best.
对于开发人员来说,不得不停下来找出另一种编码风格的额外时间纯粹是浪费时间。当您因间距、缩进和支架位置而陷入困境时,这是一个想法溜走的机会。归根结底,这些事情都无关紧要。但是让我告诉你,如果它们导致开发人员中断他们的流程,它们就很重要。所以我们需要一种方法来让他们避开障碍,让开发人员做他们最擅长的事情。
At the same time, we were digging into JavaScript a lot more. A new language where style was generally thrown out the window. Code was copy/pasted from example sites and mashed together. When learning to develop complex code in a new language, it made sense to find a way to make our JS look similar to our PHP. We can minimise it later, but we needed to be able to switch between languages quickly, again to keep our flow.
与此同时,我们更多地研究了 JavaScript。一种新的语言,风格通常被抛出窗外。代码是从示例站点复制/粘贴并混合在一起的。当学习用一种新语言开发复杂的代码时,找到一种方法让我们的 JS 看起来类似于我们的 PHP 是有意义的。我们可以稍后将其最小化,但我们需要能够在语言之间快速切换,再次保持我们的流程。
So PHP_CodeSniffer was born to do that. It helps developers work to the same coding style to make formatting and other flame-bait issues move completely out of the way. It allows you to treat your JS like your PHP to an extent. I use it to detect product-specific smells like non-translated strings or developers not using our proper class inclusion code. I also use it for language-specific smells like making sure that JS comma that kills IE isn't left around. You can use it for whatever you want. It comes with heaps of sniffs that are easy to merge together using the XML ruleset file. You can also write your own. You can integrate 3rd-party tools to make it a one-stop-shop for static code analysis. You can be as serious about standards and code smells as you like.
所以 PHP_CodeSniffer 就是为了做到这一点而生的。它帮助开发人员使用相同的编码风格,使格式和其他诱饵问题完全摆脱困境。它允许你在某种程度上像对待 PHP 一样对待你的 JS。我使用它来检测特定于产品的气味,例如未翻译的字符串或开发人员未使用我们正确的类包含代码。我还将它用于特定于语言的气味,例如确保不会留下杀死 IE 的 JS 逗号。您可以随心所欲地使用它。它带有大量的嗅探,使用XML 规则集文件很容易将它们合并在一起。你也可以自己写。您可以集成第 3 方工具,使其成为静态代码分析的一站式商店。您可以根据自己的喜好认真对待标准和代码异味。
PHP_CodeSniffer, like any dev tool, should work for you. You don't work for it. If it produces too many errors that you don't care about, customise the standard to remove the ones you don't want, or turn the errors into warnings. But if my story sounds like something you're going through or might go through in the future, it's worth taking a close look at PHP_CodeSniffer to see if it can help you.
PHP_CodeSniffer 与任何开发工具一样,应该适合您。你不为它工作。如果它产生太多您不关心的错误,请自定义标准以删除您不想要的错误,或者将错误转换为警告。但是,如果我的故事听起来像您正在经历或将来可能经历的事情,那么值得仔细研究 PHP_CodeSniffer,看看它是否可以帮助您。
I hope that helps you, and others, understand why coding standards are really important to some projects and developers. It's not about the detail. It's about removing coding style from the list of things that cause developers to lose focus.
我希望这能帮助您和其他人理解为什么编码标准对某些项目和开发人员非常重要。这不是关于细节。这是关于从导致开发人员失去焦点的事情列表中删除编码风格。
回答by molf
Having coding style conventions is a good idea, because it helps developers not get distracted by code written in a different style when working on code they did not write. It will make your code base superficially cleaner. It's great if you can automate it, but there is usually no need to go through great lengths to comply (unless the current style is terrible). If you already have a good-enough standard, stick to it.
拥有编码风格约定是一个好主意,因为它可以帮助开发人员在处理他们没有编写的代码时不会被以不同风格编写的代码分心。它将使您的代码库表面上更干净。如果您可以将其自动化,那就太好了,但通常不需要花费大量时间来遵守(除非当前的风格很糟糕)。如果你已经有一个足够好的标准,坚持下去。
Code smell is something different though: it is (a set of) symptoms that may indicate a deeper problem with the code. Examples are cyclomatic complexity, long method names, large classes, undescriptive names, duplicate code, etc. This is usually much more problematic, as it may thoroughly hurt the maintainability of your code. You should definitely solve these problems.
但是代码异味是不同的:它是(一组)症状,可能表明代码存在更深层次的问题。示例包括圈复杂度、长方法名称、大类、未描述名称、重复代码等。这通常会带来更多问题,因为它可能会彻底损害代码的可维护性。你绝对应该解决这些问题。
PHP CodeSniffer appears to be mainly developed for checking style conventions, not code smell. If you can use it to help enforce style conventions, great. But beware that it will not make your code base substantially better. You will want to do manual reviews to accomplish that.
PHP CodeSniffer 似乎主要是为了检查风格约定而不是代码气味而开发的。如果您可以使用它来帮助强制执行样式约定,那就太好了。但请注意,它不会使您的代码库显着改善。您将需要进行手动来实现这一目标。
If you want to use it to check if you comply to your currentstandard, that appears to be possible, see the answer to the question "I don't agree with your coding standards! Can I make PHP_CodeSniffer enforce my own?" in their FAQ.
如果您想使用它来检查您是否符合当前的标准,这似乎是可能的,请参阅问题“我不同意您的编码标准!我可以让 PHP_CodeSniffer 强制执行我自己的标准吗?”的答案。在他们的常见问题解答中。
回答by Jeff Dickey
Count me in among those who evangelise CodeSniffer. After being highly sceptical for years, I now use it on every project I'm working on. Why?
把我算作那些向 CodeSniffer 传福音的人。经过多年的高度怀疑,我现在在我正在从事的每个项目中使用它。为什么?
As Grace Hopper and/or Andrew Tanenbaum famously said,
正如 Grace Hopper 和/或 Andrew Tanenbaum 所说,
The wonderful thing about standards is that you have so many to choose from.
标准的美妙之处在于您有很多可供选择。
Likewise, it's almost always a Bad Idea™ to create your own coding standard; creating one comprehensive enough to cover all your code is hard, and, much more importantly, it will not be to the liking of the next person to maintain your code, who will try to "improve" your standard so that it suits his long-held coding style. Adopting an appropriateoutside standard, whether it's Zend or PEAR or Kohana or JoeBobBriggsAndHisFifthCousin, allows you to concentrate on the contentrather than the formatting. Better still, tools like PHP CodeSniffer either support the standard "fresh out of the tin" or those who have gone before have almost certainly implemented support as an add-on.
同样,创建自己的编码标准几乎总是一个坏主意™;创建一个足以涵盖您所有代码的全面性是困难的,而且更重要的是,维护您的代码的下一个人不会喜欢,他将尝试“改进”您的标准以使其适合他的长期 -保持编码风格。采用适当的外部标准,无论是 Zend、PEAR、Kohana 还是 JoeBobBriggsAndHisFifthCousin,都可以让您专注于内容而不是格式。更好的是,像 PHP CodeSniffer 这样的工具要么支持标准的“新鲜出炉”,要么那些以前使用过的工具几乎可以肯定地将支持作为附加组件实现。
Mixing coding standards with existing code not written to that standard will give you fits, unless you adopt two simple, complementary rules.
将编码标准与未按照该标准编写的现有代码相结合将使您适应,除非您采用两个简单的互补规则。
Exclude files which predate your adoption of the coding standard from being checked, through the
--ignorecommand-line option or equivalent configuration-file settings. But, when you do modify any partof a source file, update the entire file to comply with your chosen standard.
通过
--ignore命令行选项或等效的配置文件设置,排除在您采用编码标准之前的文件被检查 。但是,当您修改源文件的任何部分时,请更新整个文件以符合您选择的标准。
I just wrote a new blog postabout this sort of thing.
回答by Kornel
There are lots of cases that require human judgement, and CodeSniffer doesn't have one.
有很多情况需要人工判断,而 CodeSniffer 没有。
Consistent brackets, indentation improve the code. Lack of space after commas in function call? Probably can be forgiven, but that's ERRORaccording to CodeSniffer.
一致的括号,缩进改进了代码。函数调用中逗号后缺少空格?可能可以原谅,但根据 CodeSniffer ,这是错误。
IMHO there are way too many errors reported by CS. Even projects that appear to have neat code can easily run into thousandsof CS issues. It quickly becomes tiring and nearly impossible to resolve all those issues, especially when it's a mix of real problems and obsesive-compulsive nonsense — both equally often marked as ERRORS.
恕我直言,CS 报告的错误太多了。即使是看起来代码整洁的项目也很容易遇到数以千计的 CS 问题。解决所有这些问题很快就会变得很累并且几乎不可能解决,尤其是当它混合了实际问题和强迫症的胡说八道时——两者通常都被标记为ERRORS。
You may be better off ignoring CS and spending time on actual improvements to the code (in terms of design, algorithms) rather than just completely superficial whitespace and comments changes (does 1-line isAlphafunction really need 8 lines of comments? Yes, if you ask CS).
您可能最好忽略 CS 并花时间对代码进行实际改进(在设计、算法方面),而不仅仅是完全表面的空白和注释更改(1 行isAlpha函数真的需要 8 行注释吗?是的,如果您问CS)。
CS can too easily become turd-polishing tool.
CS 太容易成为抛光工具。
回答by DavidWinterbottom
This is definitely a good thing. We run ours from an SVN hook so that all code has to pass the house standard (a modification from PEAR) before it can be committed (this was one of the best decisions I ever made).
这绝对是一件好事。我们从 SVN 钩子运行我们的代码,以便所有代码在提交之前都必须通过内部标准(来自 PEAR 的修改)(这是我做过的最好的决定之一)。
Of course, this works best for a new project, where there isn't loads of legacy code to convert to the new standard. One way around this is modify your SVN pre-commit hook to only run new additions to the codesniffer and to ignore modifications. You can do this by adding the line:
当然,这最适用于没有大量遗留代码要转换为新标准的新项目。解决此问题的一种方法是修改您的 SVN 预提交挂钩,以仅运行新添加到代码嗅探器的内容并忽略修改。您可以通过添加以下行来做到这一点:
$SVNLOOK changed "$REPOS" -t "$TXN" | grep "^A.*\.php " > /dev/null || exit 0
This will exit the hook script if there isn't a new PHP code to parse. Hence all new files will need to obey the standard and you can bring the legacy code up to the standard in your own time.
如果没有要解析的新 PHP 代码,这将退出钩子脚本。因此,所有新文件都需要遵守标准,您可以在自己的时间使遗留代码达到标准。
回答by Tchule
Note that if you are using Eclipse or Zend IDE you can benefit from automatic tools that makes the respect of a standard less costly. You can also use a continuous integration tool like Hudson or PHPUndercontrol.
请注意,如果您使用 Eclipse 或 Zend IDE,您可以从自动化工具中受益,这些工具使遵守标准的成本更低。您还可以使用像 Hudson 或 PHPUndercontrol 这样的持续集成工具。
- PDT is a cool editor for PHP
- PDT-Tools are some plugins for PDT with an automatic formatting tool
- DTLK (Dynamic Toolkit Library) can be used to launch some external scripts to check your files.
- PDT 是一个很酷的 PHP 编辑器
- PDT-Tools 是一些带有自动格式化工具的 PDT 插件
- DTLK(动态工具包库)可用于启动一些外部脚本来检查您的文件。
You can also have a look at PHP Checkstylewhich I think is easier to configure (disclaimer : I've worked on it)
你也可以看看PHP Checkstyle,我认为它更容易配置(免责声明:我已经研究过了)
Some other tools are listed on the "documentation" page of the web site.
网站的“文档”页面上列出了其他一些工具。
回答by Sven
CodeSniffer is a great thing to implement, but you have to know how to use it. Unless you have to comply with a given coding standard because you are submitting your work to some external project, you are free to completely define your own coding standards.
CodeSniffer 是一个很好的实现,但你必须知道如何使用它。除非您必须遵守给定的编码标准,因为您将工作提交给某个外部项目,否则您可以完全定义自己的编码标准。
PHP CodeSniffer should make this very easy for you, because there are already many single code sniffs that you can include in your own coding standard definition and need not write them from scratch. While exploring the possibilities of the existing Codesniffers, you might end up writing an extension to an existing sniff or one sniff on your own, if you feel the need.
PHP CodeSniffer 应该让这对您来说非常容易,因为已经有许多单一的代码嗅探器可以包含在您自己的编码标准定义中,而无需从头开始编写它们。在探索现有 Codesniffer 的可能性时,如果您觉得需要,您可能最终会为现有嗅探或自己的一个嗅探编写扩展。
If you want to start with CodeSniffer, first step would be to grab a set of sniffs that completely resemble your current coding standards, and check the resulting errors and warnings. Don't apply one of the predefined standards, as this will most likely result in too many errors with too few benefit if fixed. For example, if you do not use PHPDoc to generate a documentation, it would be no use to fulfill all the codesniffer errors about missing PHPDoc tags and comments.
如果您想从 CodeSniffer 开始,第一步是获取一组与您当前的编码标准完全相似的嗅探,并检查由此产生的错误和警告。不要应用预定义的标准之一,因为如果修复,这很可能会导致太多错误而收益太少。例如,如果您不使用 PHPDoc 来生成文档,那么解决所有关于缺少 PHPDoc 标签和注释的代码嗅探器错误将毫无用处。
回答by nategood
Are you providing PEAR packages for public distribution thru PEAR/PECL? If so then you probably want to stick to PEAR conventions.
您是否通过 PEAR/PECL 提供 PEAR 软件包以供公共分发?如果是这样,那么您可能想要坚持 PEAR 约定。
Otherwise, I can't see it being worth the big refactor. The biggest thing is agreeing upon a coding standard for your team... doesn't have to be PEAR's standard... just make sure there is some standard convention enforced.
否则,我认为进行大重构是不值得的。最重要的是就您的团队的编码标准达成一致……不必是 PEAR 的标准……只需确保执行一些标准约定即可。
For instance, I'm a fan of the
例如,我是一个粉丝
function foo () {
format vs the PEAR standard..
格式与 PEAR 标准..
function foo ()
{
Bottom line, don't worry too much about conforming to their standard if its going to be a ton of work, especially if you aren't putting the packages on PECL.
最重要的是,如果要进行大量工作,请不要太担心是否符合他们的标准,特别是如果您没有将包放在 PECL 上。

