2 MINUTE READ | April 18, 2016
Getting started with some PHP Best Practices
As we code we all develop our own personal way of writing code, however there are a few best practices we should always follow. Following these practices not only makes it easier for others to read your code, but also easier for future you to understand what is going on. Here is a list of some of the standards you should follow when writing PHP:
Pick your application name wiselyWhen creating a new application or package, it’s important you pick the name of it wisely, doing a little research beforehand to see whehter the name is already taken. This will help other people find your app easily. For example, Twig is an existing and popular PHP templating engine, calling your app “twig” would not be a good idea.
Use PSR-4: AutoloaderPSR-4 is a coding standard recommended by PHP-Fig (Framework Interop Group). The standard outlines specifications for autoloading classes. It includes things like you MUST include top-level namespaces and all class names MUST be referenced in a case-insensitive fashion. You can read the full list of specifications here.
Follow a coding style (PSR-1 and PSR-2)PSR-1 is a basic coding standard. PSR-2 is a coding style guide which extends and expands on PSR-1. Following these guidelines ensures your code is easy to read, add to, and modify. It keeps your code consistent across all your projects, along with existing PHP open source projects as they follow these standards too. The standards specify things like where you should include blank lines, using 4 spaces rather than tab indentation, and where to place your curly brackets after methods vs. expressions.
Put your application code in an /src/ folderWhile putting your application source code in an src folder is not a requirement, it is a common trend. By following this it lets other developers know exactly where to go which is very helpful. For example, your project root will look similar to the following:
Use ComposerComposer is a Dependency Manager for PHP. If you’re creating a package/library, you should distribute it via Composer. Similarly, if you’re creating an application you should require your dependencies using Composer. If your project depends on a library you have declared using Composer, it will manage the update and install of them for you.
Stay in touch
Subscribe to our newsletter
These are just a few of the PHP best practices, you can find more on PHP-FIG and the PHP Package Checklist.
Posted by: Emily Fox
4 MINUTES READ | November 2, 2021
2 MINUTES READ | February 4, 2020
8 MINUTES READ | September 3, 2019
3 MINUTES READ | June 6, 2019
4 MINUTES READ | March 6, 2019