magmasoftwareengineering / slim-middleware-phpdebugbar
A Slim Framework middleware module for PHPDebugBar
Package info
bitbucket.org/magmasoftwareengineering/slim-middleware-phpdebugbar
pkg:composer/magmasoftwareengineering/slim-middleware-phpdebugbar
Requires
- php: >=8.3
- ext-pdo: *
- doctrine/dbal: ^3.8 || ^4.0
- doctrine/orm: ^2.19 || ^3.2
- magmasoftwareengineering/slim-base: ^3.0
- magmasoftwareengineering/slim-module-middleware: ^1.1 || ^2.0
- monolog/monolog: ^3.6
- php-debugbar/doctrine-bridge: ^3.0
- php-debugbar/monolog-bridge: ^1.0@beta
- php-debugbar/php-debugbar: ^3.0
- php-debugbar/symfony-bridge: ^1.1
- php-debugbar/twig-bridge: ^2.0
- predis/predis: ^2.2
- psr/http-message: ^1.0 || ^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- slim/http-cache: ^1.1
- symfony/mailer: ^7.1
Requires (Dev)
This package is auto-updated.
Last update: 2026-05-21 00:03:14 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.0magmasoftwareengineering/slim-module-middleware:^1.1- And their dependencies
Configuration
Basic Setup
- 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
],
];
- Configure in .env:
DEBUGBAR_ENABLE=true
DEBUGBAR_CACHE=true
- 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
Enable only in development:
'DEBUGBAR_ENABLE' => getenv('APP_ENV') === 'dev',Use Redis for persistent storage (optional):
'DEBUGBAR_CACHE' => getenv('APP_ENV') === 'dev' && getenv('REDIS_ENABLED') === 'true',Disable in load testing to avoid skewing metrics
Monitor memory usage for long-running processes
Debug Bar Panels
The middleware provides these standard panels:
| Panel | Purpose |
|---|---|
| Messages | Log messages from application code |
| Timeline | Request/response timeline with timings |
| Exceptions | Any exceptions thrown during request |
| Database | All database queries with analysis |
| PDO | PDO statement info |
| Logs | Monolog logs captured |
| Config | Framework configuration info |
| Request | HTTP request details |
| Response | HTTP response details |
Related Libraries
- Slim Base Library - HTTP controllers
- Slim Module Middleware - Module system
- Doctrine Base - Database integration
- Rollout Group Slim - Feature flagging
Troubleshooting
Debug Bar Not Appearing
Check
DEBUGBAR_ENABLEis set totrue:echo $DEBUGBAR_ENABLE # Should print "true"Verify module is in middleware list:
'middleware' => [ 'MagmaSoftwareEngineering\\PhpDebugBar', ],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