从部分视图重定向到Codeigniter中的show_404

4
我正在使用CodeIgniter中的HMVC模式。我有一个控制器通过modules::run()函数加载了两个模块,每个模块都传递了一个参数。
如果任何一个模块不能匹配传递的参数,我想调用show_404()。它可以工作,但它会在我的现有模板中加载完整的错误页面HTML,导致HTML混乱且难看。我想重定向到错误页面,这样它就不会运行第二个模块。有没有办法做到这一点而不改变URL?
是否可能仅从模块重定向到show_404()而不更改URL?
以下是正在发生的简单示例:
www.example.com/users/profile/usernamehere 该URL调用用户控制器中的此函数:
function profile($username)
{
    echo modules::run('user/details', $username);
    echo modules::run('user/friends', $username);
}

这些模块运行并检查用户是否存在:

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);
}

我想可能有更好的方法,但我没有看到。 有什么想法吗?


你可以抛出一个异常来代替使用 show_404(),然后在控制器中捕获该异常并在那里执行 show_404()。如果没有异常,就同时输出这两个结果。无需重定向。 - Zombaya
3个回答

15
你可以在子模块中出现错误时抛出异常,并在控制器中捕获该异常,然后执行 show_404()

控制器:

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

子模块:

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);
}

1
是的,我永远不会想到那一点。谢谢! - Justin

0
您可以使用此函数来重定向404未找到页面。
    if ( ! file_exists('application/search/'.$page.'.php')) {
        show_404(); // redirect to 404 page
    }

-4

非常简单,我解决了这个问题

请注意控制器名称的首字母必须大写,例如

一个带有页面的控制器应该是Pages

还要将控制器文件保存为同名的Pages.php而不是pages.php,模型类也是如此

享受吧


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接