I have a Slim 4 project with many databases.
One global for all the users : PDO $db
and one for each user : PDO $dbUser
When a user signs in I use $db to find the user and get some information. It works
Once the user is signed in I need to create / update the $dbUser with some user information.
In dependencies.php I add a definition for a connexion proxy with 2 dbs
declare(strict_types=1);
use App\Components\ConnectionProxy;
use DI\ContainerBuilder;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
LoggerInterface::class => function (ContainerInterface $c) {
$settings = $c->get('settings');
$loggerSettings = $settings['logger'];
$logger = new Logger($loggerSettings['name']);
$processor = new UidProcessor();
$logger->pushProcessor($processor);
$handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
$logger->pushHandler($handler);
return $logger;
},
PDO::class => function () {
return new PDO('mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8', getenv('DB_USER'), getenv('DB_PASS'));
},
ConnectionProxy::class => function (ContainerInterface $c) {
return new ConnectionProxy(
$c->get('db'),
$c->get('dbUser')
);
},
'db' => function (ContainerInterface $c) {
return new PDO('mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8', getenv('DB_USER'), getenv('DB_PASS'));
},
'dbUser' => function (ContainerInterface $c) {
return new PDO('mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8', getenv('DB_USER'), getenv('DB_PASS'));
},
]);
};
in signinAction.php once the user is logged in I try to update $dbUser
protected function action(): Response
{
...
$this->container->set(
'dbUser',
function () {
$db_dsn = 'mysql:host=' . getenv('DB_HOST') . ';dbname=' . $_SESSION['db_user']. ';charset=utf8';
$db_user = $_SESSION['user'];
$db_password = 'somepassword';
return new PDO($db_dsn, $db_user, $db_password);
},
);
but when I tried to use it in a repo, $dbUser is not updated, still the value from the dependencies
OneRepository.php
private $dbUser;
public function __construct(ConnectionProxy $connectionProxy)
{
$this->dbUser = $connectionProxy->getPdoUser();
}
When we add a definition in a container, is it mutable or not ?
How can I set a PDO $dbUser once the user is logged in ?