问题
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