Welcome Guest, Not a member yet? Register   Sign In
Parameters to Controller index()
#1

[eluser]insub2[/eluser]
What is the easiest way/most automated way to send data from the URL to the index function of a controller so that other methods still work?

I'd prefers something that doesn't require me to list out all of my methods. Also, I'd like to avoid messing with routes.php.

The scenario is basically...
Code:
class Post extends Controller
{

index($ID)

write()

edit($ID)

etc.
}
#2

[eluser]Colin Williams[/eluser]
_remap() baby! I rarely write a controller without one.

Code:
class Post extends Controller
{

function _remap($method)
{
  if (method_exists($this, $method))
  {
    $this->$method();
  }
  else {
    $this->index($method);
  }
}

index($ID)

write()

edit($ID)

etc.
}

You could make it more robust (like pass all URI params to index()) but that's the gist.
#3

[eluser]insub2[/eluser]
Thanks for your response. That is close but darn _remap doesn't accept more than one argument and also breaks the standard URI segment passing (e.g. function foo($arg1, $arg2) ).

What I really want is for URL http://fake-domain.com/controller/one/two/three/etc to check if one is a method. If yes, act completely normally 100% (without having to use $this->uri->segment(n) ). If not, act as if "index/" had been inserted before "one".
#4

[eluser]Colin Williams[/eluser]
Very easy solutions to those problems (that's what I meant by making it more robust).

So, voila!:

Code:
function _remap($method)
{
  $param_offset = 2;

  // Default to index
  if ( ! method_exists($this, $method))
  {
    // We need one more param
    $param_offset = 1;
    $method = 'index';
  }

  // Since all we get is $method, load up everything else in the URI
  $params = array_slice($this->uri->rsegment_array(), $param_offset);

  // Call the determined method with all params
  call_user_func_array(array($this, $method), $params);
}
#5

[eluser]insub2[/eluser]
OMG Thanks! You are the coolest!
#6

[eluser]Colin Williams[/eluser]
No problem. Clear, concise questions and requests here typically get good responses. So, thank you for being a good asker.
#7

[eluser]Unknown[/eluser]
Thanks.
#8

[eluser]puzzlebox[/eluser]
wow this is really cool.. I could use this one on my project.. Smile




Theme © iAndrew 2016 - Forum software by © MyBB