Cannot update request in Slim container

I have multi language URI such as /en-US/my-path

I can update $_SERVER[‘REQUEST_URI’] to /my-path successfully to prevent those language URI to be mess with.

But I cannot update the request in Container class.

echo $request->getUri()->getPath()."...<br>\n";

$request2 = $this->CI->request;
echo $request2->getUri()->getPath()."...<br>\n";

From the code above the first $request is from the route or controller, its result is “my-path…” which is correctly.
But the second $request or $request2 is get from Container class, its result is “en-US/my-path…” which is incorrect!

How to update the request in container class so that I can access it anywhere with the same values?

I’m not sure I’m following everything, but I’ll take a stab at an answer. The Request object cannot be fully changed. It is an immutable value object (See 'The Request` in the Slim docs.)

You can clone it and update it with certain attributes, as seen in that docs link above.

My guess based on what I think you are trying to do would be to take an approach something like this…

$originalPath = $request->getUri()->getPath(); // = /en-US/my-path
$newPath = substr($originalPath, 6); // = /mypath
$request = $request->withAttribute('newPath' $newPath);

// Later in your code when you need the path...
$newPath = $request->getAttribute('newPath');

I use…

// update uri to request.
$uri = $uri->withPath($new_path);
$request = $request->withUri($uri);
// remove and then set new "request".
$this->CI->offsetSet('request', $request);

Add after this topic How to apply new $_SERVER['REQUEST_URI'] to Slim?

Since the Request is immutable, I don’t believe you can update it in the container. That’s why you clone the Request and then pass it along down the app chain, referring to the updated $request rather than fetching the original from the container. I recall Request will be removed from the container in Slim v4.

Yes, I use offsetUnset and then offsetSet and it works!

$request = $this->CI->get('request');
echo $request->getUri()->getPath();// my-path, means it works!