Pass Object through Routes


#1

I am using Slim framework With parse server php SDK

I want to pass current user object after user login the parse server How I can retrieve this object in any routes in Slim $app? So I can identify the user


#2

I would do that with Middleware. It might look something like this.

<?php

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

/**
 * Example middleware to attach user to the Request Object
 *
 * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
 * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
 * @param  callable                                 $next     Next middleware
 *
 * @return \Psr\Http\Message\ResponseInterface
 */
public function __invoke(Request $request, Response $response, $next) {
    $user = 'user'; // user object here instead of 'user'
    $request = $request->withAttribute('user', $user);

    $response = $next($request, $response);

    return $response;
};

Then the user object becomes part of the request object which will be passed along to any controller or action classes you may have.


#3

This can work But,if I use this i need to login in parse server every request to get the current user object ?


#4

Yes, but there are other options. I will add the user object (or a portion thereof) to the session to avoid trips back to the database. That could work for you as well.


#5

starting the session in the top of index.php file solve the problem
I can now access the Current user object from parse server php sdk

Thanks :relaxed: