在PHP-DI6中注册Slim的PHP-View组件
Hey there, I get exactly where you're stuck—you just need that one clear step to inject Slim's PHP-View into your controller without dealing with outdated Twig tutorials. Let's keep this straightforward, no extra stuff you don't need:
First, make sure you've installed all required packages via Composer:
composer require slim/slim php-di/php-di php-di/slim-bridge slim/php-view
Step 1: Configure the PHP-DI Container & Slim App
Start by initializing your container and registering the PhpRenderer (Slim's PHP-View) as a service. This tells PHP-DI how to create the view instance when it's needed.
use DI\Container; use Slim\Factory\AppFactory; use Slim\Views\PhpRenderer; // Initialize PHP-DI container $container = new Container(); // Register PHP-View with your views directory path $container->set(PhpRenderer::class, function () { // Adjust the path to match where your .php view files live return new PhpRenderer(__DIR__ . '/../views'); }); // Tell Slim to use PHP-DI as its dependency container AppFactory::setContainer($container); $app = AppFactory::create();
Step 2: Build Your Controller with Constructor Injection
Your controller only needs to declare the PhpRenderer as a constructor parameter—PHP-DI will automatically inject the instance we registered earlier.
use Slim\Views\PhpRenderer; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; class HomeController { private $view; // Inject PhpRenderer directly into the controller public function __construct(PhpRenderer $view) { $this->view = $view; } // Example action that uses the view to render a template public function index(Request $request, Response $response) { // Render your view file (e.g., views/home.php) with data return $this->view->render($response, 'home.php', [ 'greeting' => 'Hello from PHP-View!' ]); } }
Step 3: Map Your Route to the Controller Action
Finally, link your route to the controller's method. Since PHP-DI handles the dependency injection, you just reference the controller class and method name.
// Register the route pointing to your controller action $app->get('/', [HomeController::class, 'index']); // Run the Slim app $app->run();
Quick Notes to Avoid Snags
- Double-check your views directory path—if the
PhpRenderercan't find your template files, you'll get an error. - If you need to add global variables to your views (like site settings), you can do it in the container registration:
$container->set(PhpRenderer::class, function () { $renderer = new PhpRenderer(__DIR__ . '/../views'); $renderer->addAttribute('siteName', 'My Slim App'); return $renderer; }); - This setup is 100% Twig-free, so you can focus on Slim and PHP-DI without extra learning overhead.
内容的提问来源于stack exchange,提问作者ConleeC

