magmasoftwareengineering/slim-middleware-phpdebugbar

A Slim Framework middleware module for PHPDebugBar

Maintainers

Package info

bitbucket.org/magmasoftwareengineering/slim-middleware-phpdebugbar

pkg:composer/magmasoftwareengineering/slim-middleware-phpdebugbar

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

1.4.0 2026-02-24 04:04 UTC

README

Version: 1.x | PHP: >=8.3 | License: MIT

Overview

The PHP DebugBar Middleware (magmasoftwareengineering/slim-middleware-phpdebugbar) integrates PHP DebugBar into Slim 4 applications as a self-contained module, providing real-time development debugging capabilities. It offers insights into database queries, caching, logging, timing, and more—all accessible through an interactive toolbar.

This library builds upon Slim Base and Slim Module Middleware to provide developer-focused debugging as a composable module that can be loaded into any Slim 4 application.

Key Features

Real-Time Debugging

  • Database profiling - Track all Doctrine queries with execution time and parameters
  • Query analysis - See duplicate queries, N+1 problems, and slow queries
  • Cache monitoring - Monitor Redis and other cache interactions
  • Logging - Integrated Monolog logging visible in debug bar
  • Timeline - Visual timeline of request/response lifecycle
  • Configuration - Server, client, and request/response parameters

Performance Metrics

  • Memory usage - Track memory consumption throughout request
  • Execution time - Detailed timing of request processing
  • Database stats - Count and duration of database queries
  • Cache stats - Hit/miss rates for caching layers

Development Tools

  • Variable inspection - Explore request/response/session data
  • Routing info - See which route matched and parameters
  • Service container - Debug dependency injection state
  • Exception tracking - Detailed error information when exceptions occur

Module Integration

  • Self-contained module - Loads as a module via Slim Module Middleware
  • Configurable - Environment-based enable/disable
  • Storage options - Redis hash storage for persistent debug data
  • HTTP cache support - ETags for efficient asset caching

Dependencies

magmasoftwareengineering/slim-base: ^3.0             (HTTP controllers)
magmasoftwareengineering/slim-module-middleware: ^1.1 (Module system)
doctrine/orm: ^2.19 || ^3.2                          (Query profiling)
doctrine/dbal: ^3.8                                  (Database access)
monolog/monolog: ^3.6                                (Logging integration)
predis/predis: ^2.2                                  (Redis storage)
symfony/mailer: ^7.1                                 (Exception mailer)
slim/http-cache: ^1.1                                (Response caching)
php-middleware/php-debug-bar: ^4.1 (dev)             (Debug bar library)

Installation

composer require --dev magmasoftwareengineering/slim-middleware-phpdebugbar:^3.0

This automatically includes:

  • magmasoftwareengineering/slim-base:^3.0
  • magmasoftwareengineering/slim-module-middleware:^1.1
  • And their dependencies

Configuration

Basic Setup

  1. Enable in settings:
<?php
// config/settings.php
return [
    'settings' => [
        // ... other settings ...

        'modules' => [
            'path' => [
                dirname(__DIR__) . '/vendor/magmasoftwareengineering',
            ],
            'middleware' => [
                'MagmaSoftwareEngineering\\PhpDebugBar',  // Load as middleware module
            ],
        ],

        // Debug bar configuration
        'DEBUGBAR_ENABLE' => getenv('DEBUGBAR_ENABLE') ?? 'false',
        'DEBUGBAR_CACHE' => getenv('DEBUGBAR_CACHE') ?? 'false',
        \DebugBar\DebugBar::class => null,  // Will be set by DI
    ],
];
  1. Configure in .env:
DEBUGBAR_ENABLE=true
DEBUGBAR_CACHE=true
  1. Register with Dependency Container:
<?php
// config/bootstrap.php
use DebugBar\StandardDebugBar;
use DI\Container;

$container->set(StandardDebugBar::class, function () {
    return new StandardDebugBar();
});

// For Redis storage (optional):
$container->set('debugbar.storage', function (Container $container) {
    return new \MagmaSoftwareEngineering\PhpDebugBar\Storage\RedisHashStorage(
        $container->get(\Predis\Client::class)
    );
});

Usage Examples

Basic Integration

The PHP DebugBar module automatically initialises when configured:

// In your Slim application, the debug bar appears at the bottom
// Shows real-time metrics and debugging information

Database Query Profiling

View all database queries executed during request:

<?php
// In your controller
public function listUsers(Request $request, Response $response): Response {
    // These queries are automatically tracked
    $users = $this->entityManager->getRepository(User::class)->findAll();

    // Debug bar will show:
    // - Query count
    // - Execution time per query
    // - SQL parameters
    // - Duplicate queries
    // - N+1 query warnings
}

Logging Integration

Monolog logs appear in the debug bar:

<?php
public function processData(Request $request, Response $response): Response {
    $this->log('Processing started');      // Logged to debug bar

    try {
        $data = $this->processComplexData();
        $this->log('Processing completed');
    } catch (Exception $e) {
        $this->log('Error: ' . $e->getMessage(), 'error');  // Error level
    }
}

Cache Monitoring

Track Redis cache interactions:

<?php
public function getProduct(Request $request, Response $response, array $args): Response {
    $productId = $args['id'];

    // Cache access is tracked in debug bar
    $product = $this->cache->get("product:$productId");

    if (!$product) {
        $product = $this->entityManager->find(Product::class, $productId);
        $this->cache->set("product:$productId", $product, 3600);
    }

    return $this->jsonResponse($response, $product);
}

Custom Debug Metrics

Add custom measurements to the debug bar:

<?php
use DebugBar\DebugBar;

public function importData(Request $request, Response $response): Response {
    $debugBar = $container->get(DebugBar::class);

    $debugBar['time']->startMeasure('import', 'Data Import');

    try {
        // Import logic
        $this->performImport($data);
    } finally {
        $debugBar['time']->stopMeasure('import');
    }

    return $this->jsonResponse($response, ['status' => 'success']);
}

Template Integration

Include debug bar in Twig templates:

{# templates/layout.twig #}
<!DOCTYPE html>
<html>
<head>
    {% if debugbar_enabled %}
        {{ dump_debugbar_css() }}
    {% endif %}
</head>
<body>
    {# Your content #}
    {{ include('components/navigation.twig') }}

    {% block content %}{% endblock %}

    {% if debugbar_enabled %}
        {{ dump_debugbar_js() }}
        {{ dump_debugbar() }}
    {% endif %}
</body>
</html>

Custom Debug Information

Store custom data in debug bar:

<?php
public function apiEndpoint(Request $request, Response $response): Response {
    $debugBar = $this->getModuleSetting(DebugBar::class);

    // Add custom messages
    $debugBar['messages']->info('User action started');

    // Store structured data
    $debugBar['messages']->debug('User data', [
        'id' => $this->getUserId(),
        'role' => $this->getUserRole(),
    ]);

    // Track variables
    $debugBar['messages']->debug('Response headers', $response->getHeaders());

    return $this->jsonResponse($response, $data);
}

Complete Application Example

Directory Structure

my-api/
├── src/
│   └── modules/
│       ├── User/
│       │   ├── src/
│       │   │   ├── Controller/
│       │   │   │   └── UserController.php
│       │   │   └── Service/
│       │   │       └── UserService.php
│       │   ├── Module.php
│       │   └── routes.php
│       └── Product/
│           ├── src/
│           │   └── Controller/
│           │       └── ProductController.php
│           ├── Module.php
│           └── routes.php
├── public/
│   └── index.php
├── config/
│   ├── bootstrap.php
│   └── settings.php
├── .env.local
└── composer.json

Configuration Files

<?php
// config/settings.php
return [
    'settings' => [
        'slim' => [
            'displayErrorDetails' => true,
        ],

        'database' => [
            'driver' => 'pdo_mysql',
            'host' => getenv('DB_HOST') ?? 'localhost',
            'user' => getenv('DB_USER') ?? 'root',
            'password' => getenv('DB_PASS') ?? '',
            'dbname' => getenv('DB_NAME') ?? 'myapp',
        ],

        'modules' => [
            'path' => [
                dirname(__DIR__) . '/src/modules',
                dirname(__DIR__) . '/vendor/magmasoftwareengineering',
            ],
            'middleware' => [
                'MagmaSoftwareEngineering\\PhpDebugBar',
            ],
            'load' => [
                'MyApp\\Modules\\User',
                'MyApp\\Modules\\Product',
            ],
        ],

        'DEBUGBAR_ENABLE' => getenv('DEBUGBAR_ENABLE') ?? 'false',
        'DEBUGBAR_CACHE' => getenv('DEBUGBAR_CACHE') ?? 'false',
        \DebugBar\DebugBar::class => null,
    ]
];
<?php
// config/bootstrap.php
use DI\Container;
use DebugBar\StandardDebugBar;
use Doctrine\ORM\EntityManagerInterface;
use Predis\Client;
use Psr\Log\LoggerInterface;
use Slim\App;

$container = new Container();

// Settings
$settings = require __DIR__ . '/settings.php';
$container->set('settings', $settings['settings']);

// Logger (Monolog)
$container->set(LoggerInterface::class, function (Container $c) {
    // ... logger setup ...
});

// Database (Doctrine)
$container->set(EntityManagerInterface::class, function (Container $c) {
    // ... Doctrine setup ...
});

// Redis for caching
$container->set(Client::class, function () {
    return new Client();
});

// Debug bar
$container->set(StandardDebugBar::class, function () {
    return new StandardDebugBar();
});

// Cache provider
$container->set('cache', function (Container $c) {
    return new \MagmaSoftwareEngineering\PhpDebugBar\Storage\RedisHashStorage(
        $c->get(Client::class)
    );
});

return $container;
# .env.local
DEBUGBAR_ENABLE=true
DEBUGBAR_CACHE=true
DB_HOST=localhost
DB_USER=root
DB_PASS=password
DB_NAME=myapp_dev

Performance Considerations

In Development

  • Enabled - Full debugging information
  • CPU impact - Moderate (query profiling adds overhead)
  • Memory impact - ~5-10MB additional per request
  • Storage - Optional Redis storage for persistent debug data

In Production

  • Disabled - Set DEBUGBAR_ENABLE=false
  • No overhead - Debug bar code is not executed
  • Storage - No debug data stored

Best Practices

  1. Enable only in development:

    'DEBUGBAR_ENABLE' => getenv('APP_ENV') === 'dev',
    
  2. Use Redis for persistent storage (optional):

    'DEBUGBAR_CACHE' => getenv('APP_ENV') === 'dev' && getenv('REDIS_ENABLED') === 'true',
    
  3. Disable in load testing to avoid skewing metrics

  4. Monitor memory usage for long-running processes

Debug Bar Panels

The middleware provides these standard panels:

PanelPurpose
MessagesLog messages from application code
TimelineRequest/response timeline with timings
ExceptionsAny exceptions thrown during request
DatabaseAll database queries with analysis
PDOPDO statement info
LogsMonolog logs captured
ConfigFramework configuration info
RequestHTTP request details
ResponseHTTP response details

Related Libraries

Troubleshooting

Debug Bar Not Appearing

  1. Check DEBUGBAR_ENABLE is set to true:

    echo $DEBUGBAR_ENABLE  # Should print "true"
    
  2. Verify module is in middleware list:

    'middleware' => [
     'MagmaSoftwareEngineering\\PhpDebugBar',
    ],
    
  3. Clear template cache if using Twig caching

High Memory Usage

  • Reduce number of captured logs
  • Disable query profiling for large result sets
  • Use Redis storage instead of in-memory storage

Database Queries Not Showing

  • Verify Doctrine is configured correctly
  • Ensure query profiler is enabled in Doctrine settings
  • Check that database connection uses profiled driver

Support & Contributing

For issues or contributions, please contact the maintainer:

  • Jeremy Coates - hello@phpcodemonkey.me.uk

License

MIT License - See LICENSE file for details