Tips for writing a better code in PHP

Salwa achek
4 min readMay 31, 2024

Keeping the code abstract and clean is very important for the maintainability of any code base.
Here i will be guiding you through some of the important steps to achieve that, to keep your PHP code efficient and reliable .

1. Stick to the PSR standards:

The PHP Standards Recommendations (PSR) offer a set of guidelines for coding standards, autoloading, and coding style.

You find below a set of the most important rules prescribed by PSR-2:

  • Indentation: Code must use 4 spaces for indentation, not tabs.
  • Blank line after the namespace : In every PHP file, There should be a blank line after the namespace declaration and each group of use statements, variables/constants declarations.
  • Braces in class and method: The opening brace for classes and methods should be on the same line and the closing brace should be on a new line.
  • Conditional statements closing brace: The closing brace for Conditional statements (if, else, for, while, etc.) must be on the same line as the condition keyword.
  • Blink line between the methods and properties: Within a class methods and properties should be separated by a blank line.
  • Method Visibility should be defined: The visibility of methods ( public, private, protected) must be declared explicitly.
  • Method calls: No space between the name and opening parenthesis of the method and there should be no space before the closing parenthesis.
  • Method Arguments: When defining method arguments, no space should be left before the opening parenthesis and after the closing parenthesis and no spaces after commas when listing the arguments.
  • Array Declaration: Arrays should be declared with [] and not using the constructor array() .
  • Single and double quotes when defining Strings: You can use both to enclose the string but the same style should be maintained throughout the codebase.
  • Concatenation: To concatenate strings, a space should be defined before and after the concatenation operator ( . ) .

2. Validate user input:

To secure your code from possible threats and attacks such as SQL injection and cross-site scripting (XSS), it’s extremely important to validate and sanitize user input independently from the identity of the user.

Below you find some basic examples to do that :

<?php 

$name = htmlspecialchars($_POST['name']);
w$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

4. Use meaningful variable and function names:

To make your code accessible to fellow developers, it must be readable and comprehensive.

Variables should be descriptive and method names should reflect the purpose and the use of it.

If a name is giving a double meaning it should not be used. this reduces the need for extensive comments to explain the code.

5. Use namespaces:

Namespaces are good to have to prevent naming conflicts and help organize your code logically.

By encapsulating classes and functions within namespaces, you make your codebase more coherent and comprehensible for other people to maintain.

6. Use exception handling:

we can not run from errors and exceptions but we can make sure that our application can handle those unexpected situations properly by handling them.

Below is an example to do that :

<?php

function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}

try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

Proper error handling not only enhances the user experience and prevent the application from crushing but also helps the developer in debugging.

7. Use an MVC design pattern:

The Model-View-Controller or shortly called MVC, is a Design pattern and a powerful tool for structuring the application. It separates concerns and that makes it so easy to maintain.

8. Use prepared statements for database queries:

Your application database can be easily targeted by SQL injection attacks. the attacker can do that through manipulating user inputs.

To prevent these kind of attacks, you can use prepared statements. they handle separating SQL code from user input.

Below is an example for using prepared statements :

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");

$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");

$id = 1;
$label = 'PHP';
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string

$stmt->execute();

9. Optimize your code:

Performance optimization is an everyday process. Its so important to keep in mind that the less the better.

Try to reduce the number of database queries, nested loops, optimize session handling, etc. and eliminate unnecessary code and resources.

10. Document your code:

Good documentation makes maintaining the code easy and accelerates the onboarding process .

You can do that through comments and documentation tools like PHPDoc to define your code’s functionality, parameters, and return values of functions.

11. Manage dependencies:

Managing project dependencies is a very important step for the maintainability of the code. For PHP we have the Composer.

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage the installation as well as the update for you.

To use Composer in your PHP project, all you need is a composer.json file. This file describes the dependencies of your project and may contain other metadata as well.

It typically should go in the top-most directory of your project repository.

Below is an example for composer.json content :

{
"require": {
"monolog/monolog": "2.0.*"
}
}

Conclusion:

Following the previous steps and tips will make your code more efficient , more secure, maintainable, and accessible to your fellow developers.

--

--

Salwa achek

A dedicated and enthusiastic backend developer with a commitment to get better everyday and a deep passion for continuous learning and self improvement.