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 wisely
When 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: Autoloader
PSR-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/ folder
While 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 Composer
Composer 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.