Welcome Guest, Not a member yet? Register   Sign In
Unsetting URI segments in CI instance
#1

I'm a contractor working on upgrading a client's application from CI1 to CI4 (4.4.4 to be precise). There is a function in the legacy code that gets a value from a URI segment and then unsets that segment so that it doesn't interfere with routing. I've looked at the HTTP URI class and segments is now a protected property (and will be private in the future) so accessing the segments property directly as this code does isn't going to continue to work. I can use getSegments for that portion of the code, but I don't know how to handle the unsetting of segments as they do in that last if statement. Is there a way to unset segments in the CI instance? Should this be handled some other way?

In the legacy code this function is in a helper which is only ever accessed from a pre-controller hook. In the new code, I'll be moving this function to a filter.

Code:
function getActiveCredential() {
        $CI =& get_instance();

        // Grab the last segment of the URL
        $lastSegment = count($CI->uri->segments);
        $activeCredential = $lastSegment > 0 ? $CI->uri->segments[$lastSegment] : null;
        $activeCredential = is_numeric($activeCredential) ? $activeCredential : null;

        // Now unset it, so it doesn't affect the controllers
        if ($lastSegment > 0 && is_numeric($activeCredential)) {
            unset($CI->uri->segments[$lastSegment]);
            unset($CI->uri->rsegments[$lastSegment]);
        }

        return $activeCredential;
    }
Reply
#2

(This post was last modified: 05-31-2024, 04:08 PM by kenjis.)

Frankly, unsetting URI segments is not good idea.
I don't get why the legacy code did such dirty hack.
You can define a route for the URIs with active credential.
You should remove the change if you can.

You cannot unset URI segments in CI4.
If you really want to do the legacy code way, you should customize the creation of URI (SiteURI) instance. https://github.com/codeigniter4/CodeIgni...#L795-L809
You get the active credential before creating the URI instance and create the URI instance without the active credential,
instead of creating URI instance with the active credential and unset a segment after that.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB