Welcome Guest, Not a member yet? Register   Sign In
[solved] Check if action exists
#1

[eluser]Velin[/eluser]
Hi there,

this feels like a silly question, which I have had no luck finding an answer to on Google, so forgive me if the answer is blatantly obvious.

Is there a clever/dynamic way to check if an action exists within the current controller?


I would like to ensure that users of a controller are unable to call any actions which are not defined within it.

I could use _remap or routing for this, but to the best of my knowledge, I would have to define each action in an array and match the second URI segment against it, and then redirect accordingly.

I also can't seem to get function_exists() to help me achieve this.


Any pointers would be welcome, thanks.
#2

[eluser]wiredesignz[/eluser]
Using a base controller with _remap() and method_exists() is the simplest I have found.

Example:
Code:
function _remap($action) {
        $this->load->vars($this->config->item('settings'));
        
        if (method_exists($this, $action)) {
            call_user_func_array(array($this, $action), array_slice($this->uri->segments, 2));
        } else {    
            modules::run('error/error404', trim($this->uri->uri_string, '/'));
        }
        
        $search = $this->load->module('search');
        $this->load->vars(array('searchBox' => $search->render()));
        
        $this->output->final_output = parser::parse($this->layout);
    }
#3

[eluser]Velin[/eluser]
That is a great solution and example.

Thank you so much.
#4

[eluser]tonanbarbarian[/eluser]
CI should automatically do this anyway.
If the method does not exist in the controller CI shows the 404 error page
#5

[eluser]wiredesignz[/eluser]
The error404 is not the only method you could use. That is only an example. You may not even want a 404 response in some cases.
#6

[eluser]Velin[/eluser]
In my opinion it's not always ideal to throw 404 pages.

Instead, I would like the site to predict which content the user wanted to access and show that instead of an error page, in certain controllers.

To do that properly, the remap has to know which actions are available, and redirect accordingly.




Theme © iAndrew 2016 - Forum software by © MyBB