8000 GitHub - jpswade/PHPBestPractices
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

jpswade/PHPBestPractices

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 

Repository files navigation

PHP Best Practices

A list of best practices tips for better PHP

CODING STANDARDS

Historically PHP developers have received bad reputations mainly due to poor coding and not escaping SQL from injection.

One way to improve the over-all quality of a product, help reduce problems, increase productivity and development and generally make life a little easier in the long run is to stick to a set of Coding Standards as closely as possible.

All projects should take the same approach and stick to one set of coding standards. This will solve many common problems, especially projects which have more than one developer.

There's lots of well established Coding Standards out there. One such is PEAR Coding Standards. PEAR is a library of useful classes for PHP, as an attempt to help users from re-inventing the wheel to achieve the same task.

PEAR has grown larger over the years and has many packages on offer, as such like everyone else some packages in PEAR had common problems. The PEAR team decided it was best to employ coding standards for everyone to work to.

PEAR, which attempted to be the standard for years now participates in PHP Standards Recommendation (PSR).

It would be worth noting the difference between "Coding Standards" and "Best Practices".

Coding Standards should be guidelines that we should be aiming to stick to, relating to the way code is written and its readability.

Best Practices, however, are recommendations that may help with security, performance, or architectural patterns that are solutions to a commonly occurring problems.

BEST PRACTICES

  1. Stick to coding standards, it will make it easier for you to understand other people's code and other people will be able to understand yours
  2. Avoid using uppercase booleans (TRUE, FALSE, NULL) as it can be difficult to debug
  3. Declare "Class Methods" visibility, precede private or protected functions with an underscore (eg: private function _test ($string) { ... })
  4. Avoid using regular expression functions (preg_), they can be slow, string functions are faster
  5. Avoid using switch/case statements, else/if is faster and often easier to read
  6. Avoid Error Control Operator (@) for error suppression, it's slow and hard to debug
  7. Avoid using print instead of echo, it's slower
  8. Use the alternative syntax, colon (:), for control structures such as 'if, while, for, foreach, and switch', when working with markup or templates
  9. Avoid "Unnecessary Closing Delimiter" (?>), this avoids outputting unwanted whitespace. Consider putting an EOF comment instead to show a deliberate end and prove that your output is working as expected.
  10. Avoid accessing the superglobals ($_GET, $_POST, $_REQUEST, etc) directly as user input cannot be trusted, consider using filter_input()
  11. Avoid too many nested blocks in functions, instead consider breaking them out into new functions
  12. Return early
  13. Avoid using the PHP mail() function direction as your mail may be subjected to header injection, PHP mail(), swiftmailer and phpmailer sucks. Try PEAR Mail instead.
  14. Avoid reinventing the wheel, Don't repeat yourself (DRY), use existing functions, extensions (PECL) libraries (PEAR), frameworks (CodeIgniter, Zend, Laravel) as they will often already be optimised
  15. Avoid using functions inside of loops, such as for ($x=0; $x < count($array); $x) as count() function would get called each time
  16. Always declare static methods, when the method has no dynamic content
  17. Use Class Constants
  18. Use full paths in includes and requires, less time spent on resolving the file system paths
  19. Avoid function calls if there's a constant or variable (eg: PHP_VERSION vs php_version() or $_SERVER['REQUEST_TIME'] vs time())
  20. Cache your web pages using systems built into your framework or a library such as PEAR Cache:Lite
  21. Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview
  22. Separate code, content and presentation: keep complex logic separate from presentation markup, akin to the Model–View–Controller (MVC) architectural pattern
  23. Learn how to store passwords safely, never store passwords as clear text or simple md5 hash, learn to use bcrypt correctly
  24. Use an IDE, the most important thing for me is the Integrated Development Environment (IDE), notepad simply won't cut it and there's plenty of great IDEs out there that support PHP, find an IDE that works with your existing toolset, try NetBeans (Free, Open Source) or JetBrains phpStorm see what works for you.
  25. Turn on error reporting, use strict code, avoid suppressing errors, notices and warnings, resulting in cleaner code and less overheads, set error_reporting(E_ALL) always on
  26. Use the standards tags when declaring PHP as all other styles are depreciated, including short tags.
  27. Upgrade to the latest version of PHP, it's (often) faster, PHP7 is the fastest yet!
  28. Avoid blindly using empty(), consider isset() or count() or strlen() if they are more appropriate
  29. The mysql_ functions are deprecated and will be removed in the future: use mysqli or PDO instead
  30. Work with automated and repeatable development environments using tools such as Vagrant, Virtualbox and Puppet makes it easy
  31. Use version control to help tame PHP projects as they scale, learn to use git, PHP is one of the most popular languages on GitHub so it's here to stay, get used to it.
  32. Document your code, use tools such as phpDocumentor
  33. Learn how to do Unit Testing using tools such as phpUnit
  34. Use the type safe comparison operators (===) to compare type and value rather than just value (==)
  35. Avoid SQL injection by not trusting user input and preparing your statements using parameterised queries (in mysqli or PDO)
  36. Avoid email address validation using complex regular expressions, consider filter_var() and FILTER_VALIDATE_EMAIL and verify the email address exists by sending a confirmation email to it
  37. Use pre-increment where possible, ++$i is faster than $i++
  38. Consider using isset() in replace of strlen() where possible, for example: if (strlen($foo) < 5) vs. if (!isset($foo{5})), language constructs are faster than functions
  39. Avoid using strip_tags(). It won't protect you against XSS (Cross-site scripting) attacks. Consider using htmlspecialchars() convert the markup to plain text.
  40. When parsing HTML or XML, don't use regular expressions, use a DOM parser
  41. Avoid using exit() or die() functions for error management, use proper error handling such as Exceptions
  42. Don't use query strings for cache control on js/css files, consider filename-based cache busting instead.
  43. To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or the MySQL DATETIME format ("Y-m-d H:i:s")
  44. Avoid using eval(). "If eval() is the answer, you're almost certainly asking the wrong question".
  45. Consider the performance of MySQL vs PHP, sometimes PHP is faster
  46. If you've got slow database queries, consider memcached.
  47. Always die() after a header Location redirect, preventing the script from continuing after the client is redirected.
  48. Avoid passing by references where possible. The unexpected nature of the sort() function is a good example of this.
  49. Use Packagist to find the right package for the job and Composer to manage your dependencies
  50. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English. Please USE IT!

QUOTES

PHP has a few quirks which we sometimes approach with best practices while they can otherwise be addressed with a quote.

Listed here are a number of quotes that may go some way to help explain why certain things are certain ways.

  • "Never memorize something that you can look up" -- Albert Einstein
  • "I'm not a real programmer. I throw together things until it works then I move on. The real programmers will say "Yeah it works but you're leaking memory everywhere. Perhaps we should fix that." I'll just restart Apache every 10 requests." -- Rasmus Lerdorf
  • "The sooner you start to code, the longer the program will take" -- Roy Carlson, University of Wisconsin
  • "PHP is just a hammer. Nobody has ever gotten rich making hammers." -- Rasmus Lerdorf
  • "Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems." -- Jamie Zawinski, in comp.lang.emacs
  • "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%" -- Donald Knuth
  • "Everything in the box is kind of weird and quirky, but maybe not enough to make it completely worthless. And there's no clear problem with the set as a whole; it still has all the tools" -- Alex Munroe
  • "The echo chamber of geeks sitting around playing with their tools means absolutely nothing to me compared to seeing the code actually saving peoples' lives" -- Rasmus Lerdorf
  • "Talk is cheap. Show me the code." -- Linus Torvalds
  • "Release early, release often" -- Eric S. Raymond
  • "A problem well stated is a problem half-solved." - Charles Kettering
  • "For many events, roughly 80% of the effects come from 20% of the causes" - Vilfredo Pareto

BOOKS

About

No description or website provided.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
0