Create a piece of code that can be called from anywhere


Here is the dumb question of the day…
Using Slim V4… Where and how should I put a piece of code that can be called from anywhere… In my case I should be able to create a JWT token…

$now = new DateTime("now");
$future = new DateTime("now +1800 seconds");
$jti = (new Base62)->encode(random_bytes(16));

$payload = [
    "jti" => $jti,
    "iat" => $now->getTimeStamp(),
    "exp" => $future->getTimeStamp()

$token = JWT::encode($payload, $secret, "HS512");
return $token

This is very basic and the piece of code should accept two incoming parameters…
Soooooo… Containers? Or not containers? :grin:

Thanks a lot in advance,


You probably want to put JWT-generating code in either a service class called upon by an action class or a middleware depending on the kind of payload you want to encode. If you are going to use JWT for auth you might want to take a look at or

If you for some reason I can’t imagine really, really want to allow anything, anywhere in your application to run a piece of code, put it in $GLOBALS, see This is a bad idea and you should not do it.

1 Like

Thanks for the reply.
I am already successfully using JWT authentication.
My issue here is to add a custom string to the payload and be able to call the JWT generation code from any Action in the framework.
I just can’t figure out where to put that piece of code that would get my custom string as input and would get the JWT string back as output.
Been struggling with “containers”, “Middleware” and stuff for the last few days and I understand that the solution is pretty straightforward.
Could someone help?

The answer is Here