Redirect to default method if CodeIgniter method doesn't exists.

心已入冬 提交于 2019-12-07 07:02:08

问题


I am using CodeignIter and am looking to for a way to write a custom handling routine for a single controller when a called method does not exist.

Lets say you call www.website.com/components/login

In the components controller, there is not a method called login, so instead of sending a 404 error, it would simply default to another method called default.


回答1:


Yes there is a solution. If you have Components controller and the flilename components.php. Write following code...

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Components extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function _remap($method, $params = array())
    {
        if (method_exists(__CLASS__, $method)) {
            $this->$method($params);
        } else {
            $this->test_default();
        }
    }

    // this method is exists
    public function test_method()
    {
        echo "Yes, I am exists.";
    }

    // this method is exists
    public function test_another($param1 = '', $param2 = '')
    {
        echo "Yes, I am with " . $param1 . " " . $param2;
    }

    // not exists - when you call /compontents/login
    public function test_default()
    {
        echo "Oh!!!, NO i am not exists.";
    }

}

Since default is PHP reserved you cannot use it so instead you can write your own default method like here test_default. This will automatically checks if method exists in your class and redirect accordingly. It also support parameters. This work perfectly for me. You can test yourself. Thanks!!



来源:https://stackoverflow.com/questions/15035716/redirect-to-default-method-if-codeigniter-method-doesnt-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!