CodeIgniter 2.1 问题与 show_404() 和 404_override [英] CodeIgniter 2.1 issue with show_404() and 404_override

查看:34
本文介绍了CodeIgniter 2.1 问题与 show_404() 和 404_override的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 CodeIgniter 已经有一段时间了,我目前正在为一个想要自定义 404 页面的客户做一个项目.一切都很好,404_override 效果很好.

I have been working with CodeIgniter for quite a while now and I'm currently doing a project for a client that would like a custom 404 page. Everything is fine and the 404_override it works great.

当访问者试图访问不存在的文章时,我的问题出现了我想调用 show_404() 函数,但这显示了 out of box" 404 页面而不是 404_override 中编写的页面.

My issue comes when a visitor is trying to access a article that do not exist I would like to call the show_404() function, but this shows me the "out of box" 404 page and not the one written in the 404_override.

我已经看到了一些针对旧版本的修复程序,但我无法在 2.1 中使用它.所以如果有人能帮我解决这个问题,我将不胜感激.

I have seen some fixes for older versions, but I can't get it to work in 2.1. So if anyone can help me out of this I would be really grateful.

推荐答案

重定向是最干净的;加载视图也可以.

Redirect is cleanest; loading a view could work too.

这里的问题是 show_404() 通常在您的控制器已经加载后调用(毕竟必须告诉它显示 404).CI 不喜欢在那个时候加载第二个控制器,这是主要障碍.

The problem here is that show_404() is usually called AFTER your controller has already loaded (something had to tell it show the 404 after all). CI doesn't like loading a second controller at that point, which is the primary hurdle.

您最好的选择可能是扩展 Exceptions 类中的 show_404() 函数以重定向到您的 404 路由.如果没有重定向,您将不得不在调用 404 之前显示视图或您知道具有所有额外数据"的内容(或者我想您也可以在 Exceptions 类中加载它).在某些动态视图中它会变得非常复杂.

Your best option probably is extending the show_404() function in the Exceptions class to redirect to your 404 route. Without a redirect, you'll be stuck with showing a view or something that you know has all the "extra data" it needs prior to calling the 404 (or I guess you could load it in the Exceptions class too). It can get really complicated in some dynamic views.

您显然想要更高级的东西,而不仅仅是在错误文件夹中编辑 404 模板.我在尝试从该文件访问 get_instance() 时遇到问题,因为有时它是在构建控制器之前加载的.所以,如果你尝试这样做,请小心;)

You obviously want something more advanced than just editing the 404 template in the errors folder. I've had problems trying to access get_instance() from that file, as sometimes it's loaded before the controller is constructed. So, be careful if you try that ;)

更新:这是一个扩展 show_404() 函数以加载视图的工作示例

Update: Here's a working example of extending the show_404() function to load a view

<?php
// application/core/MY_Exceptions.php
class MY_Exceptions extends CI_Exceptions {

    public function show_404()
    {
        $CI =& get_instance();
        $CI->load->view('my_notfound_view');
        echo $CI->output->get_output();
        exit;
    }
}

这篇关于CodeIgniter 2.1 问题与 show_404() 和 404_override的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆