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

查看:538
本文介绍了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.

您最好的选择可能是扩展异常类中的show_404()函数重定向到您的404路线。没有重定向,你会坚持显示一个视图或者你知道有所有额外的数据,它需要之前调用404(或者我猜你可以加载它在异常类)。在一些动态视图中它可能变得非常复杂。

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天全站免登陆