I am trying to figure out how I can have a global variable, in this case a variable similar to a Java hashtable (or hashmap). For now I simply want to stick the userid and name in the global hashmap after each user login.
Then lookup the name in some later code.
The hashmap needs to be global singleton.
I did some research and have 2 ideas below. What do you think?
// index.php (set global hashmap):
$container = $app->getContainer();
$container[‘allusers’] = function () {
return array(); // singleton?
};
// routes.php (after sign in set userid, name in hashmap):
$container[‘allusers’][$userid] = $name;
// routes.php (other routes, get the user name)
$uname = $container[‘allusers’][$userid]
$app->container->singleton(‘allusers’, function (){ // not sure if this works in slim 3?
return array();
});
$container[‘allusers’] = function () {
return new \Slim\Collection();
};
I can’t access the Collection in routes.php. I have tried the statements below. Getting undefined variable for the first two and a 500 error with no message for the 3rd.
This gets the collection from the container. But it is getting a new and empty Collection each time. I was wanting to get the same Collection object. To build up the Collection over multiple requests.
The documentation says it should return a singleton. But each time I get it it is empty ???
The container definition is:
$container[‘allusers’] = function () {
return new \Slim\Collection();
};
The second question is, where does var_dump() and print_r() actually log to??
I am using wamp server and not seeing anything in the wamp logs or slim app log. ??
But it is getting a new and empty Collection each time.
In PHP a singleton is only the same within the same request/response cycle.
To build up the Collection over multiple requests.
Well, this is not how PHP works. PHP is stateless (like the web). Everything’s is getting rebuilt and/or reloaded on each request. Unfortunately the only way to remotely have some kind of stateful processing in PHP is by using of sessions (and indirectly cookies). And even if you use the session to save your state it will have to be rebuilt on the next request.
var_dump() and print_r() are PHP internal functions to print the content of variables. By default the output goes directly into the output buffer. Some people use this functions for debugging Slim is based on PSR-7 and the output is handled internally via Resources. That’s why you should use the Slim Response ($response) object to generate an output for the client. I would recommend Monolog for logging.