PHP Web Framework Mezzio

PHP Web Framework Mezzio Starter App
On 3 min, 29 sec read

Getting Started with Mezzio: A Modern Middleware Framework for PHP

Mezzio is an open-source microframework developed by the Laminas Project. It provides a middleware-based architecture that is perfect for building scalable and maintainable web applications in PHP. If you’re looking for a modern alternative to traditional MVC frameworks, Mezzio offers flexibility, performance, and the backing of a strong PHP community.

What is Mezzio?

Mezzio is built around the concept of middleware, giving developers the ability to compose applications from reusable components. It’s PSR-7 and PSR-15 compliant, which means it works seamlessly with modern PHP standards for HTTP message interfaces and middleware.

  • Middleware architecture for clean and modular code
  • Support for multiple routing, templating, and dependency injection containers
  • PSR-compliant, interoperable with a wide range of PHP libraries
  • Ideal for REST APIs and microservices

Installing Mezzio

To get started, you’ll need PHP 8.1 or higher, Composer, and a web server such as Apache or Nginx.




composer create-project mezzio/mezzio-skeleton my-app
cd my-app
composer serve
  

The installer will prompt you to select your preferred container, router, and template engine. Once complete, your application will be accessible at http://localhost:8080.

Building a Simple Database Application with Mezzio and PDO

In this section, we’ll build a basic Mezzio middleware that connects to an existing MySQL database using PDO and returns data from a table in JSON format.

Step 1: Configure the Database Connection




return [
    'db' => [
        'dsn'      => 'mysql:host=localhost;dbname=my_database;charset=utf8mb4',
        'username' => 'my_user',
        'password' => 'my_password',
    ],
];
  

Step 2: Create a PDO Service Factory




namespace App\Factory;

use Psr\Container\ContainerInterface;
use PDO;

class PdoFactory
{
    public function __invoke(ContainerInterface $container): PDO
    {
        $config = $container->get('config')['db'];

        return new PDO(
            $config['dsn'],
            $config['username'],
            $config['password'],
            [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]
        );
    }
}
  

Step 3: Register the PDO Service




return [
    'dependencies' => [
        'factories' => [
            PDO::class => \App\Factory\PdoFactory::class,
        ],
    ],
];
  

Step 4: Create Middleware to Fetch Data




namespace App\Handler;

use PDO;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Laminas\Diactoros\Response\JsonResponse;

class UserListHandler implements RequestHandlerInterface
{
    private PDO $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $stmt = $this->pdo->query('SELECT id, name, email FROM users');
        $users = $stmt->fetchAll();

        return new JsonResponse($users);
    }
}
  

Step 5: Register the Route




use App\Handler\UserListHandler;

$app->get('/users', UserListHandler::class, 'users.list');
  

Visit /users to see the user list output as JSON.

Screenshots

Mezzio Installation
Composer Installing Sample Mezzio Application

Mezzio Server
Mezzio Web Server Running

Mezzio Twig Template
Web Browser Displaying Custom Mezzio Twig Template Page

Watch the Live Screencast

Watch the full step-by-step Mezzio installation and configuration process

Go Deeper with the Learning PHP Course

Want to master PHP from the ground up? Enroll in my course “Learning PHP”, designed for beginners and intermediate developers. It covers everything from syntax to building full applications, including Mezzio projects like the one above.

The book version of Learning PHP is also available and includes code walkthroughs, diagrams, and exercises to reinforce your understanding.

Enroll in the course or buy the book.

Book a One-on-One PHP or Mezzio Tutorial

If you’d prefer a more personalized approach, I offer one-on-one coaching sessions. Whether you’re just getting started or working on a Mezzio project, I can help you gain clarity and confidence.

Contact me to schedule your session.

Conclusion

Mezzio provides a modern and efficient framework for PHP developers who want more control and flexibility in building web applications. From middleware composition to dependency injection and database integration with PDO, it’s a framework that grows with your needs.

Explore the screencast, try the code examples, and check out the Learning PHP course to deepen your skills.

🚀 Recommended Resources


Disclosure: Some of the links above are referral links. I may earn a commission if you make a purchase at no extra cost to you.

About Edward

Edward is a software engineer, author, and designer dedicated to providing the actionable blueprints and real-world tools needed to navigate a shifting economic landscape.

With a provocative focus on the evolution of technology—boldly declaring that “programming is dead”—Edward’s latest work, The Recession Business Blueprint, serves as a strategic guide for modern entrepreneurship. His bibliography also includes Mastering Blender Python API and The Algorithmic Serpent.

Beyond the page, Edward produces open-source tool review videos and provides practical resources for the “build it yourself” movement.

📚 Explore His Books – Visit the Book Shop to grab your copies today.

💼 Need Support? – Learn more about Services and the ways to benefit from his expertise.

🔨 Build it Yourself – Download Free Plans for Backyard Structures, Small Living, and Woodworking.