Reputation: 345
I am trying to create my own little MVC system, its working very well, but one thing i have problems with is parsing variables to methods.
You see i use URL rewritting to make every url point at index.php, and then set up the page by the url data like /email/1/34/
I am then creating an object such as here.
<?php
$page = $urlsplit[0];
$variables = array($urlsplit[1], $urlsplit[2]);
$page->callmethod($variables);
?>
What i want it to do is that instead of parsing the array to the method, it should do it like this.
$page->callmethod($variables[0], $variables[1]);
Any idea how i can do this?
Upvotes: 2
Views: 169
Reputation: 58444
Actually , it would make more sense to use some kind of regular expression for splitting the URL in multiple parts.
Consider this fragment:
/*
$url = '/user/4/edit'; // from $_GET
*/
$pattern = '/(?P<controller>[a-z]+)(:?\/(?:(?P<id>[0-9]+)\/)?(?P<action>[a-z]+))?/';
if ( !preg_match( $pattern, $url, $segments ) )
{
// pattern did not match
}
$controller = new $segments['controller'];
if ( method_exists( $controller, $segments['action'] ) )
{
$action = $segments['action'];
$param = $segments['id'];
}
else
{
$controller = new ErrorController;
$action = 'notFound';
$param = $url;
}
$response = $controller->$action( $param );
Of course in a real MVC implementation there would be additional things going on, but this should explain the concept.
Upvotes: 0
Reputation: 111299
To make a call like $page->callmethod($variables[0], $variables[1])
dynamically you can use call_user_func_array
:
call_user_func_array(array($page, 'callmethod'), $variables);
Upvotes: 2