Blog

PSR-2 or how to be a better developer

15-04-2021 · in development

PSR-2 or how to be a better developer

In the PHP world the entire community was not so compact in the early days when it comes to the coding standards. The idea of having a coding standard is so hard to adopt to some of us and it is causing more trouble in the thinking process.
This is so evident when doing code reviews for example and can cause different useless talks inside the development team.

Advantages

PHP Standard Requirements (PSR) is the the go to point for any kind of PHP developer. From my experience I can say that adopting a code standard like PSR-2 comes with multiple benefits. I will try to list them here:

- software maintenance; this is the main point and the most important one. If you do a search you can find that from the cost perspective between 40 and 80 percent of the lifetime cost of a software goes into maintenance and also the fact the hardly any software is maintained its whole life by the author.

- code quality; software development work involves reading a lot of code. Either writing code or code review involves reading the code and this should not be perceived as something difficult to do or more beautifully said, as something annoying.

- keep it simple; the complexity of a code structure is fighting against security in most cases. If you try to minimize the amount of code written during the project development you will also write less (hidden) bugs

- refactoring; when renaming a variable, renaming a method or breaking code in smaller parts it is called refactoring. When the code looks clean and ordered then the refactoring process goes easy and well.

- code language; every developer should know English. All the documentations regarding parts of some software are in English. The guy coding after you knows also English so for all of the reasons above the code language is connected with the software maintenance process and is bringing a plus to the readability of the code.

PSR-2 conventions

The PSR-2 conventions make a lot of sense for me at least in overall code improvement.

Indenting

I read a lot of articles with talks about what is better, tab or spaces. For PSR-2 things are simple in my perspective: “Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting.”.

Properties

Developers know that naming variables is the hardest thing to do so thinks like “Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.” or like “Visibility MUST be declared on all properties.” are here to help.

Closures

“Closures MUST be declared with a space after the function keyword, and a space before and after the use keyword.” To check out all the conventions for the PSR-2 standard please visit this link

Tools

A great tool to have some automation in checking the code standards is PHP CodeSniffer. To install it you can do something like

	apt install php-codesniffer

or if you have PEAR installed

	pear install PHP_CodeSniffer

After installation you can use it from the console for example like this

	phpcs --standard=PSR2 src/

Or you can set up your IDE to automatically check the coding standard using the phpcs.

Go ahead and be a better PHP developer

A good developer should follow a code standard. I am standing up for PSR-2 here but what code standard you should use it is up to you. The important thing is to have one and follow it strictly.

If you are a business owner or project owner talk with your developers about coding standards.
If you are a developer adopt a coding standard.

source1 source2 source3

What is new in PHP8.3?

22-11-2023 · in development

php 8.3 news

Revolutionizing JSON Validation with json_validate

Embarking on a journey through the extensive history of PHP, a language I've navigated for quite some time, crafting and revising thousands of lines of code. PHP, a stalwart language, is now set to unveil its latest iteration, version 8.3, slated for an official release by month-end. In this discourse, we delve into the pivotal modifications characterizing this upcoming release.

Revolutionizing JSON Validation with json_validate

php 8.3 json_validate

The perennial question – is it JSON or not? Traditionally, one would resort to parsing the entirety using json_decode, awaiting confirmation of validity. Yet, the latest version introduces a game-changer: the json_validate function. This innovation promises the same accuracy but with significantly reduced resource consumption.

Streamlining Error Management in unserialize

php 8.3 unserialize exception

The notorious unserialize() function, renowned for its erratic error generation from E_NOTICE to E_WARNING, is undergoing a paradigm shift in version 8.3. Expect consistent throws every time, eliminating the need to handle the nuances of E_NOTICE.

Unveiling the #[Override] Attribute

php 8.3 override attribute

A valuable addition surfaces – the #[Override] attribute. Its primary utility lies in detecting methods that potentially override a counterpart in the parent class. Notably, it now triggers an error if the method in the parent class undergoes a name change, rendering the #Override-labeled method non-overriding.

Dynamic Connections to Class Constants

php 8.2 constants

Prior to version 8.3, the loading of class constants remained a static or Reflection1-driven affair. With the advent of 8.3, a dynamic approach emerges, allowing the loading of these constants with variable interpolation.

php 8.3 constants

Evolving Read-only Property Handling in the __clone() Process

In a prior release, PHP embraced the concept of declaring read-only properties during class instantiation. However, when it came to cloning, these properties faced constraints, limited to superficial duplication.

php 8.3 change read only properties in order to clone

Version 8.3 dismantles these restrictions, enabling effective cloning of read-only properties within the context of the __clone() method. Beyond these pivotal updates, the PHP landscape undergoes additional shifts – the introduction of specific errors during DateInterval object initialization, such as DateMalformedIntervalStringException, enhancements to the mb_str_pad function, and notable performance boosts for array_sum() and array_product().

PHP 8.3 was released on November 23, 2023. It will be tested through three alpha releases, three beta, and six release candidates.

For a comprehensive overview of all the alterations, refer to php.net

Git Tip: Efficient File Staging with Interactive Mode

05-02-2024 · in development

Git Tip: Efficient File Staging with Interactive Mode

Ever found yourself with a heap of files in Git, pondering whether to add them individually or just bulk add everything with git add .? Here's a smarter approach: use Git's interactive mode.

Step-by-Step Guide:

  1. Start with a Status Check: Begin by checking your repository status with git status. Imagine you're faced with 50 modifiable files.
  2. Enter Interactive Mode: Instead of manually adding files one by one, initiate Git's interactive mode by running git add -i. This is especially handy when you have a specific subset of files to stage.
  3. Select Files to Stage: Once in interactive mode, select the 'update' option by pressing 'u'. Now, you’re presented with the list of your modified files. To stage files, you have flexible options:
    • To add a single file, simply enter its corresponding number and hit enter.
    • For multiple files, type their numbers separated by spaces (e.g., '2 3') or a comma (e.g., '2,3').
    • To stage a range of files, use a dash (e.g., '1-3') to select files 1 to 3 inclusively.
  4. Finalize the Staging: After making your selections, a subsequent git status will show all chosen files neatly staged and ready for commit. This method allows for precise control over what gets staged, streamlining the process significantly.

PHP Namespaces or How to Organize Your Code

07-06-2024 · in development

Code clarity should not just be a goal, it should be a standard. To help achieve this, we must explore PHP namespaces, a powerful feature that brings order and structure to your code. Imagine namespaces as the silent librarians of PHP, ensuring that everything is in its right place, preventing conflicts, and keeping the codebase clean.

What Are PHP Namespaces?

Namespaces in PHP are designated areas that allow you to group related code elements like classes, interfaces, functions, constants, enums, and traits. They encapsulate these elements to ensure that names are unique within a given context. Think of namespaces as the directories on a computer—without them, there would be no way to distinguish between items with the same name.

Real-Life Example

Consider a library as an analogy. In a library, books are organized into sections based on genres like fiction, non-fiction, science, and history. Inside each section, books are further categorized by authors and titles. You could find a book titled "The Great Adventure" in both the fiction and non-fiction sections, but because they are categorized under different genres, there’s no confusion about which book you’re referring to when you specify its section.

In this scenario, each genre acts like a namespace, and the books represent different classes or functions within that namespace. Just as the library’s organization system prevents confusion over book titles, PHP namespaces prevent confusion over class names or function names, allowing developers to use the same name in different “sections” of their code without any mix-ups.

The Syntax of Namespaces

To utilize namespaces in PHP, you need to understand the syntax that defines and references them. Here’s how it works:

Declaring a Namespace

At its simplest, a namespace is declared at the beginning of a PHP file using the namespace keyword followed by the desired name of the namespace. It must be the first statement in the file, before any other code, except for a declare statement:

image.png 10.52 KB
In the example above, the User class is part of the MyProject namespace, similar to filing this class under a folder named MyProject.

Referencing a Namespace

When you want to use a class or function from a namespace, you reference it by its full name, which includes the namespace:

image.png 12.47 KB
Using Sub-namespaces

Namespaces can be hierarchical. Here’s how you declare a class within a sub-namespace:

image.png 14.06 KB
Here, the Connection class is within the Database sub-namespace under the main MyProject namespace.

Importing Namespaces

To avoid writing out long namespace names every time, PHP offers the use keyword to import a namespace:

image.png 18.41 KB

By importing the Connection class with the use statement, we can reference it more succinctly.

Using Aliases

Sometimes class names get lengthy. For convenience, you can use aliases:

image.png 22.54 KB
Aliases are especially useful when your project contains two classes with the same name under different namespaces.

Autoloading with Namespaces

In PHP, “autoloading” allows for the automatic loading of class files whenever they’re needed, eliminating the need for manual require or include statements. Namespaces enhance this process by providing a structured, predictable path to class files.

PSR-4 Autoloading Standard

The PHP community has adopted the PSR-4 standard for autoloading, which pairs seamlessly with namespaces. It dictates that each namespace should correspond to a directory structure.

For example, a class MyProject\Database\Connection should be located in a file MyProject/Database/Connection.php, relative to a designated base directory.

Composer and Autoloading

Composer, a dependency manager for PHP, provides a powerful and flexible autoloader out of the box. By default, it uses the PSR-4 standard for autoloading classes. You define the mapping between your namespaces and directories in the composer.json file.

image.png 20.22 KB
With this configuration, Composer will automatically load any class within the App namespace from the app/ directory, and so on.

Putting It All Together

Once you’ve defined your autoloading rules in composer.json, run composer dump-autoload to generate the vendor/autoload.php file. Including this file in your project (usually in the root of the project index.php file) sets up autoloading for your entire application.

image.png 19.63 KB

Namespaces in Action

Accessing Static Methods

image.png 36.13 KB
Group Use Declarations

image.png 42.74 KB
Calling Namespaced Functions

image.png 51.33 KB
Embracing namespaces in PHP is a decisive step towards writing clearer, more organized code. They solve the age-old problem of name collisions and pave the way for larger, more complex applications. Now, knowing how to declare, import, and use namespaces, you are better equipped to keep your codebase tidy and conflict-free. Namespaces are not just a feature; they are an essential practice in the modern PHP developer’s workflow.