Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to show_404 in Codeigniter from a partial view

I am using the HMVC pattern in CodeIgniter. I have a controller that loads 2 modules via modules::run() function and a parameter is passed to each module.

If either module cannot match the passed paramter I want to call show_404(). It works, but it loads the full HTML of the error page within my existing template so the HTML breaks and looks terrible. I think I want it to redirect to the error page so it doesn't run the 2nd module. Is there some way to do that and not change the URL?

Is it possible to just redirect to show_404() from the module without changing the URL?

Here is an over simplified example of what's going on:

www.example.com/users/profile/usernamehere

The url calls this function in the users controller:

function profile($username)
{
    echo modules::run('user/details', $username);
    echo modules::run('user/friends', $username);
}

Which run these modules, which find out if user exists or not:

function details($username)
{
    $details = lookup_user($username);
    if($details == 'User Not Found')
        show_404(); // This seems to display within the template when what I want is for it to redirect
    else
        $this->load->view('details', $details);
}

function friends($username)
{
    $details = lookup_user($username);
    if($friends == 'User Not Found')
        show_404(); // Redundant, I know, just added for this example
    else
        $this->load->view('friends', $friends);
}

I imagine there is just a better way to go at it, but I am not seeing it. Any ideas?

like image 915
Justin Avatar asked Dec 26 '22 21:12

Justin


1 Answers

You could throw an exception if there was an error in a submodule and catch this in your controller where you would do show_404() then.

Controller:

function profile($username)
{
    try{
       $out  = modules::run('user/details', $username);
       $out .= modules::run('user/friends', $username);
       echo $out;
    }
    catch(Exception $e){
       show_404();
    }
}

Submodule:

function details($username)
{
    $details = lookup_user($username);
    if($details == 'User Not Found')
        throw new Exception();
    else
        // Added third parameter as true to be able to return the data, instead of outputting it directly.
        return $this->load->view('details', $details,true);
}

function friends($username)
{
    $details = lookup_user($username);
    if($friends == 'User Not Found')
        throw new Exception();
    else
        return $this->load->view('friends', $friends,true);
}
like image 170
Zombaya Avatar answered Mar 12 '23 20:03

Zombaya