Current Location: Home> Latest Articles> Implementing PSR2 and PSR4 Standards in the Fat-Free Framework

Implementing PSR2 and PSR4 Standards in the Fat-Free Framework

M66 2025-06-30

The Importance of Standardized PHP Development

As PHP continues to evolve and expand across various applications, writing standardized code has become essential for long-term maintainability and team collaboration. The PHP-FIG group introduced a series of coding standards, with PSR2 and PSR4 being two of the most fundamental. This article focuses on how these standards can be applied and promoted within the Fat-Free Framework, complete with relevant code examples.

Applying PSR2 in the Fat-Free Framework

PSR2 focuses on code style and formatting, covering indentation, naming conventions, bracket positioning, and more. In the Fat-Free Framework, adhering to PSR2 is straightforward and helps maintain a consistent coding style across a team. For example, developers should use four-space indentation and camelCase naming, as shown below:

<?php
class ExampleController extends Controller
{
    public function index()
    {
        $name = 'John';

        if ($name == 'John') {
            echo 'Hello, John!';
        } else {
            echo 'Hello, guest!';
        }
    }
}

Following PSR2 ensures consistency, improves readability, and makes code easier to maintain and review by others.

Implementing PSR4 Autoloading in Fat-Free

PSR4 deals with class autoloading using namespaces and directory structures. With Composer, PSR4 allows automatic loading of classes without manual require statements.

Start by adding the following configuration to your composer.json file in the project root:

{
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        }
    }
}

After saving the file, run the following command in the terminal to generate the autoload files:

composer dump-autoload

Then, create a class under the app/ directory using the App namespace:

<?php
namespace App;

class ExampleClass
{
    public function hello()
    {
        echo 'Hello, World!';
    }
}

You can now use the class directly in your application without manual imports:

<?php
$app = new App\ExampleClass();
$app->hello();

This approach simplifies class management, improves structure, and enhances scalability.

Conclusion

Adopting PSR2 and PSR4 in the Fat-Free Framework offers tangible benefits. PSR2 promotes clean, consistent, and readable code, while PSR4 enables efficient autoloading and modular design via Composer. These standards help teams collaborate more effectively and empower developers to write modern, maintainable PHP applications.

By incorporating these practices, developers can elevate both their code quality and overall development workflow within the Fat-Free Framework.