Reference for writing clear PHP code

Overview

clearPHP

Reference for writing clear PHP code

It is difficult to know when one's code is well written. There are recommendations for writing PHP code in the manual, from CS theories, peers review, and gut feeling. That makes a lot of rules.

The main goal of this document is to collect such rules, so as to have them all easy to read and select them for reviewing one's code. This is a reference document, in which anyone may look for ways to improve their code.

Read the clearPHP rules.

So Many Rules

There are obviously a lot of rules. And probably some will be added soon.

  • This is no ultimate coding standard : claiming that any code is 100% compatible with the current reference is futile. No medals are eventually distributed.
  • Don't use them all : it would be difficult to apply them all at the same time in one code. This is because some rules generates too many observations (try to educate quotes), some may be contradictory.
  • It is fine to hate some rules : this is a reference. Its first goal is to collect their rules, their description, their advantages and drawbacks. After this, you'll be able to adopt some of them. This also means that you will dislike some rules : this is OK.

License

Unless stated otherwise, all content is licensed under the Creative Commons Attribution License.

A copy of the license is included in the repository.

Acknowledgements

ClearPHP was originally written by Damien Seguy. The following people have contributed to this project:

Comments
  • no-dangling-commas

    no-dangling-commas

    This is just bad advice.

    1.) Indentation here is messed up.

    $array = array('a', 
                      'b',
                     );
    $array2 = ['c', 
                 'd',
                ];
    

    What is going on there? :)

    2.) You have a copy paste error in The following pattern is considered legit:

    $array = array('a', 
                      'b'
                     );
    
    $array2 = ['c', 'd', ];
    

    I guess that $array2 was supposed to have the , removed?

    Either way, trailing commas on multi-line array definitions are awesome. They are also supported in pretty much every language I've used, but are banned in JSON.

    They are a style guide choice for sure, but a) they don't hurt at all, and b) they reduce friction and potential conflicts in diffs. I've seen a LOT of conflicts caused by just this, and since asking developers on various teams to use trailing diffs those problems have gone away.

    I'd like to see this one deleted entirely.

    opened by philsturgeon 9
  • Do Not Include Closing PHP Tag In Example Code

    Do Not Include Closing PHP Tag In Example Code

    We shouldn't encourage people to include a closing php by including it in the examples. This is because if someone writes a php class and then puts a new line character after the closing tag, php will send the response - not the desired behaviour at all!

    opened by GrahamCampbell 8
  • Always Ha(ve|s) Visibility and Interfaces

    Always Ha(ve|s) Visibility and Interfaces

    The title in the document is wrong, however, the rule is missing one important point: Interfaces

    Members of an interface are per language specification always public and any other visibility makes no sense. Hence, requiring the visibility to be defined is redundant and (imho) should actually be avoided for clarity.

    opened by Fleshgrinder 6
  • Feature/consistency and spelling

    Feature/consistency and spelling

    Changes are along the lines of:

    • Correcting grammer and spelling errors
    • Fix some blatant copy/paste errors
    • Removing PHP closing tags if not needed to demonstrate a point (to be in line with the no-closing-tags rule)
    • Removing unused/commented out headers (to be in line with no-commented-out-code rule - lead by example)
    • Small markdown use improvements, mainly for consistency:
      • adding code backticks
      • removing code backticks from non code phrases, replacing them by underscores to make the text cursive
      • make functions in phrases always have (), and remove them for most language constructs
      • consistent use of bullets and fixed where they would not be recognized as such
      • simplify table layouts
    • Added some additional Further Reading links
    • Make links to PHP manual language agnostic

    As this is quite a huge PR, I have purposefully split it in functional commits for easier review. Please see the notes on the individual commits for more information.

    opened by jrfnl 5
  • avoid-those-slow-functions has some bad replacements

    avoid-those-slow-functions has some bad replacements

    How should someone e.g. remove in_array() with isset() when the first function operates on values, while the other could only check for a key. You might advice someone trying to use the isset(), but it's not really a possible replacement. Same is true of diff/intersect on arrays.

    Replacing array_walk() and array_map() with a foreach-by-reference could cause some side effects as mentioned in the PHP Pitfalls document you linked to. Although the foreach-by-reference is a lot faster, the usage of the other functions is necessary if you use clean and readable functional programming techniques.

    opened by 2ndkauboy 4
  • No Eval

    No Eval

    Not entirely sure what the point of this is.

    https://github.com/dseguy/clearPHP/blob/master/rules/no-eval.md#rule-details

    It doesn't really explain what is happening, and if its good or bad.

    Also you say:

    Such code has to be systematically sanitized before it is used.

    It's impossible to sanitize eval from user input securely.

    http://stackoverflow.com/questions/5922762/eval-base64-decode-php-virus

    http://stackoverflow.com/a/3697776

    Best to just NEVER put user input anywhere near eval.

    opened by philsturgeon 4
  • Error text in Imported collision

    Error text in Imported collision

    In https://github.com/dseguy/clearPHP/blob/master/rules/imported-collision.md#rule-details block last code sample with $a,$b,$c,$d,$e,$f is obviously not considered warnings

    opened by u-mulder 2
  • Mess with code example in Avoid Redefining Properties

    Mess with code example in Avoid Redefining Properties

    Just before the first code sample we have (https://github.com/dseguy/clearPHP/blob/master/rules/avoid-redefining-properties.md#avoid-redefining-properties) Check the code below : $lock is defined in a class But there's no $lock variable. And nothing about vehicle too,

    opened by u-mulder 2
  • no-hardcoded-credential - suggest solutions

    no-hardcoded-credential - suggest solutions

    Things like https://github.com/vlucas/phpdotenv are a great solution to this sort of problem, and it's a framework agnostic (or no framework) solution. Laravel builds on top of it, as do others no doubt.

    opened by philsturgeon 2
  • No Sleep - Fine in CLI

    No Sleep - Fine in CLI

    Maybe mention you don't want to put sleep in web facing code specifically, but it's ok in CLI stuff.

    https://github.com/dseguy/clearPHP/blob/master/rules/no-sleep.md

    Sleep can be pretty handy in big cron jobs when you're doing batch imports and dont want to utterly flood your database.

    opened by philsturgeon 2
  • Fix Contributor Links for Derick Rethans

    Fix Contributor Links for Derick Rethans

    I'm not sure where "kitsched" came from, but I'm confident that "derickr" is the contributor that was intended to be included.

    Made these quick edits through github, sorry for the commit spam.

    opened by jrchamp 1
  • Avoid direct include or require in spl_autoload_register

    Avoid direct include or require in spl_autoload_register

    In https://github.com/dseguy/clearPHP/blob/master/rules/use-smart-autoload.md example:

    function my_autoloader($class) { include 'classes/' . $class . '.class.php'; }

    For every include that fail, will generate a warning and increase your log. If you have 4 functions (methods,..) registered using include directly, will create 4 warnings for every request.

    It is worse with require, that create a fatal error and stop the execution.

    It 's a shame than spl_autoload_register don't work like include_path, that try every path and show the error if all fail.

    opened by joanhey 2
  • Two rules which are essentially the same ?

    Two rules which are essentially the same ?

    When going through everything, I noticed that these two are essentially the same. If they are not (supposed to be), then maybe the difference between the two rules should be made clearer. If they are, I suggest merging them into one rule.

    https://github.com/dseguy/clearPHP/blob/master/rules/no-buried-assignation.md https://github.com/dseguy/clearPHP/blob/master/rules/no-implied-if.md

    opened by jrfnl 2
  • Whitespace

    Whitespace

    Currently are all examples, pattern without space between brackets and var. I think is also a good practice to write readable code. Maybe I would check all examples for this and send a pull request with the changes - if you like it?

    Example:

    if (!$foo) {
    

    much better

    if ( ! $foo ) {
    

    Also I would add a chapter about space, whitespace in code for better legibility, if you like?

    opened by bueltge 4
  • no-double-quote

    no-double-quote

    While you have linked to Nikita's article Disproving the Single Quotes Performance Myth, your advice is still incredibly generalized and not entirely accurate.

    I wrote this up on PHP The Right Way: Strings

    Scroll down to this bit:

    Which is quicker? There is a myth floating around that single quote strings are fractionally quicker than double quote strings. This is fundamentally not true.

    If you are defining a single string and not trying to concatenate values or anything complicated, then either a single or double quoted string will be entirely identical. Neither are quicker.

    If you are concatenating multiple strings of any type, or interpolate values into a double quoted string, then the results can vary. If you are working with a small number of values, concatenation is minutely faster. With a lot of values, interpolating is minutely faster.

    Regardless of what you are doing with strings, none of the types will ever have any noticeable impact on your application. Trying to rewrite code to use one or the other is always an exercise in futility, so avoid this micro- optimization unless you really understand the meaning and impact of the differences.

    opened by philsturgeon 0
Owner
Seguy Damien
Seguy Damien
Result of our code-along meetup writing PHP 8.1 code

PHP 8.1 Demo Code This code demonstrates various PHP 8.0 and 8.1 features in a realistic, functional (but incomplete) codebase. The code is part of so

azPHP 2 Nov 14, 2021
Test essentials for writing testable code that interacts with Magento core modules

Essentials for testing Magento 2 modules Using mocking frameworks for testing Magento 2 modules is counterproductive as you replicate line by line you

EcomDev B.V. 9 Oct 6, 2022
PHP OOP interface for writing Slack Block Kit messages and modals

Slack Block Kit for PHP ?? For formatting messages and modals for Slack using their Block Kit syntax via an OOP interface ?? By Jeremy Lindblom (@jere

Slack PHP Framework 32 Dec 20, 2022
A library for reading and writing DNA test kit files in PHP.

php-dna Requirements php-dna 1.0+ requires PHP 8.0 (or later). Installation There are two ways of installing php-dna. Composer To install php-dna in y

Family Tree 365 4 Aug 31, 2022
PHP implementation for reading and writing Apache Parquet files/streams

php-parquet This is the first parquet file format reader/writer implementation in PHP, based on the Thrift sources provided by the Apache Foundation.

null 17 Oct 25, 2022
A pure PHP library for reading and writing presentations documents

Branch Master : Branch Develop : PHPPresentation is a library written in pure PHP that provides a set of classes to write to different presentation fi

PHPOffice 1.2k Jan 2, 2023
Dead Code Detector (DCD) for PHP code.

This project is no longer maintained and its repository is only kept for archival purposes. PHP Dead Code Detector (PHPDCD) phpdcd is a Dead Code Dete

Sebastian Bergmann 406 Dec 30, 2022
⚗️ Adds code analysis to Laravel improving developer productivity and code quality.

⚗️ About Larastan Larastan was created by Can Vural and Nuno Maduro, got artwork designed by @Caneco, is maintained by Can Vural, Nuno Maduro, and Vik

Nuno Maduro 4.4k Jan 4, 2023
Free ZIP Code API - Free Access to Worldwide Postal Code Data

About Zipcodebase - Free Zip Code API Zipcodebase is a zip code API that was founded in 2019 to solve common issues with postal code data. As we have

SaaS Industries 2 Nov 26, 2022
Preload your sweet sweet code to opcache with a composer command, making your code faster to run.

Composer Preload Preload your sweet sweet code to opcache with a composer command, making your code run faster. Composer Preload is a composer plugin

Ayesh Karunaratne 197 Dec 6, 2022
The SensioLabs DeprecationDetector runs a static code analysis against your project's source code to find usages of deprecated methods, classes and interfaces

SensioLabs DeprecationDetector CAUTION: This package is abandoned and will no longer receive any updates. The SensioLabs DeprecationDetector runs a st

QOSSMIC GmbH 389 Nov 24, 2022
Webman quickly creates a verification code tool similar to Google verification code

webman-captcha-grid webman quickly creates a verification code tool similar to Google verification code webman 快速创建一个类似于 Google 点图验证码的本地验证码扩展 介绍 webma

听风吹雨 6 Dec 5, 2022
Code to accompany the YouTube video "Full PHP cURL API tutorial - how to use a REST API from PHP using cURL"

PHP cURL CRUD Example Example code to accompany this YouTube video. Note that the init_curl.php file contains a placeholder for an API key. DO NOT che

Dave Hollingworth 14 Dec 24, 2022
The VarExporter component allows exporting any serializable PHP data structure to plain PHP code.

The VarExporter component allows exporting any serializable PHP data structure to plain PHP code. While doing so, it preserves all the semantics associated with the serialization mechanism of PHP (__wakeup, __sleep, Serializable).

Symfony 1.8k Jan 1, 2023
A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.

A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.

Felix Becker 1.1k Jan 4, 2023
Clean Code concepts adapted for PHP - A guide for producing readable, reusable, and refactorable PHP software

Clean Code concepts adapted for PHP - A guide for producing readable, reusable, and refactorable PHP software

Fabio Soares 172 Dec 25, 2022
Check modules in app/code and vendor for PHP 8 compatibility status - PHP_CodeSniffer & php-compatibility standard

M2 PHP version compatibility check How To use Requires PHP 7.3+ | PHP 8 This app will run PHP_CodeSniffer with phpcompatibility/php-compatibility on t

William Tran 24 Oct 13, 2022