slimphp / PHP-View

A Simple PHP Renderer for Slim 3 & 4 (or any other PSR-7 project)
MIT License
263 stars 60 forks source link

$_SESSION global variable is not available when rendering $content #64

Closed scsmash3r closed 4 months ago

scsmash3r commented 4 years ago

How to reproduce:

$_SESSION['user_id'] = 'some_value';

$phpView = new PhpRenderer("path/to/templates", ["title" => "My App"]);
$phpView->setLayout("layout.php");

//...

$phpview->render($response, "hello.php", ["title" => "Hello - My App", "name" => "John"]);

In hello.php:

<?php var_dump($_SESSION); // Will not be set ?>
Hello <?=$name?>! Your id is: <?= $_SESSION['user_id'] ?>

In layout.php:

<?php var_dump($_SESSION); // Will be filled as intended ?>
<html><head><title><?=$title?></title></head><body><?=$content?></body></html>

So, in both hello.php and layout.php you will be able to get $title var. But, in hello.php global $_SESSION var will be empty. Expected behavior would be leaving global variables intact.

twogood commented 3 years ago

If you need the session in whole or in part you should send it as a parameter to the render method.

odan commented 4 months ago

All templates values should (must) be passed into the template. The template should not fetch data from the upper layers in MVC. So global- and "Super-Global" variables such as $_SESSION should not be used within a template.