Logo

dev-resources.site

for different kinds of informations.

PSR-4: Autoloading Standard in PHP

Published at
1/11/2025
Categories
php
standards
phpfig
Author
jonesrussell
Categories
3 categories in total
php
open
standards
open
phpfig
open
Author
12 person written this
jonesrussell
open
PSR-4: Autoloading Standard in PHP

Ahnii!

Remember the old days of PHP when we had to manually require every single file? πŸ˜… Last week, I was helping a team modernize their legacy application that had 50+ require statements at the top of each file. Let me show you how PSR-4 autoloading makes this a problem of the past!

Understanding PSR-4 (5 minutes)

Think of PSR-4 as your code’s GPS system - it helps PHP find the right files automatically. Just like how a GPS uses addresses to find locations, PSR-4 uses namespaces to locate classes.

Key Concepts (2 minutes)

  1. πŸ“ Fully Qualified Class Name (FQCN)
    • Vendor namespace (like your brand)
    • Package namespace (like your project)
    • Class name (the actual file)
  2. πŸ“ Directory Structure
    • Base directory (where everything starts)
    • Namespace mapping (your GPS coordinates)
    • File location rules (the actual addresses)

Real-World Example (10 minutes)

Here’s how I structure my projects:

vendor/
└── jonesrussell/
    └── blog/
        β”œβ”€β”€ composer.json
        └── src/
            └── Post/
                β”œβ”€β”€ PostController.php
                └── PostRepository.php

Enter fullscreen mode Exit fullscreen mode

1. Setting Up Composer (3 minutes)

{
    "name": "jonesrussell/blog",
    "autoload": {
        "psr-4": {
            "JonesRussell\\Blog\\": "src/"
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

2. Creating Classes (2 minutes)

<?php

namespace JonesRussell\Blog\Post;

class PostController
{
    public function index()
    {
        return ['status' => 'Ready to blog!'];
    }
}

Enter fullscreen mode Exit fullscreen mode

Common Patterns I Use (5 minutes)

1. 🎯 Multiple Namespace Roots

{
    "autoload": {
        "psr-4": {
            "JonesRussell\\Blog\\": "src/",
            "JonesRussell\\Blog\\Tests\\": "tests/"
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

2. 🌳 Nested Namespaces

<?php

namespace JonesRussell\Blog\Core\Database;

class Connection
{
    private $config;

    public function __construct(array $config)
    {
        $this->config = $config;
    }
}

// File location: src/Core/Database/Connection.php

Enter fullscreen mode Exit fullscreen mode

Framework Examples (5 minutes)

If you’re using Laravel or Symfony (like I do), they follow PSR-4 out of the box:

Laravel

<?php

namespace App\Http\Controllers;

class BlogController extends Controller
{
    public function index()
    {
        return view('blog.index');
    }
}

Enter fullscreen mode Exit fullscreen mode

Symfony

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class BlogController extends AbstractController
{
    public function index(): Response
    {
        return $this->render('blog/index.html.twig');
    }
}

Enter fullscreen mode Exit fullscreen mode

Quick Fixes for Common Issues (3 minutes)

  1. πŸ” β€œClass Not Found” Errors
# When things go wrong, this is your friend:
composer dump-autoload

Enter fullscreen mode Exit fullscreen mode
  1. 🎯 Directory Structure Mistakes
# Don't do this
src/
└── controllers/ # lowercase = bad
    └── PostController.php

# Do this instead
src/
└── Controller/ # Matches namespace case
    └── PostController.php

Enter fullscreen mode Exit fullscreen mode

Testing Your Setup (2 minutes)

Drop this in test-autoload.php:

<?php

require 'vendor/autoload.php';

// If this works, your autoloading is set up correctly!
$controller = new \JonesRussell\Blog\Post\PostController();
var_dump($controller->index()); // Should show "Ready to blog!"

Enter fullscreen mode Exit fullscreen mode

Next Steps

Tomorrow, we’ll explore PSR-6 and see how it standardizes caching in PHP applications. This post is part of our PSR Standards in PHP series.

Resources

standards Article's
30 articles in total
Favicon
PSR-6: Caching Interface in PHP
Favicon
PSR-4: Autoloading Standard in PHP
Favicon
PSR-3: Logger Interface in PHP
Favicon
PSR Standards in PHP: A Practical Guide for Developers
Favicon
PSR-1: Basic Coding Standard in PHP
Favicon
Anvil: An attempt of saving time
Favicon
Wednesday Links - Edition 2024-03-27
Favicon
The TAG, and Responsible Innovation on the Web
Favicon
2023 Industry Trends in Mobile Application User Interface
Favicon
Becoming W3C Games Community Group co-chair
Favicon
Jim's Guide to CockroachDB Naming Standards
Favicon
Writing Code with Standards and generate report on PreCommit : PHP / Laravel Project
Favicon
Creating a code style guide
Favicon
Call for Mentors for the Web Mapping Code Sprint: 29/11 - 01/12 2022 πŸŽ“
Favicon
Apeleg join the W3C
Favicon
2. Green Mode Design: Implementation Strategies
Favicon
Call for Mentors for the Vector Data Code Sprint: 12-14 July 2022 πŸŽ“
Favicon
Re-evaluating technology
Favicon
Web development is like assembling IKEA furniture
Favicon
Introducing the Email Markup Consortium (EMC)
Favicon
Pizza Code
Favicon
Estilo de código no PHP: as recomendaçáes da PSR-1 e PSR-12
Favicon
Today, the distant future
Favicon
PHPArkitect: Put your architectural rules under test!
Favicon
Cross browser speech synthesis - the hard way and the easy way
Favicon
Foundations
Favicon
XML, making everything just a little bit harder.
Favicon
Coding Standards and Naming Conventions
Favicon
Portals and giant carousels
Favicon
Continuous partial browser support

Featured ones: