2

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?

3
  • $page->callmethod($urlsplit[1], $urlsplit[2]); no? Commented Mar 31, 2012 at 20:38
  • A suggestion here for SEO its better when you have some information in the url so perhaps its better when you try something like this "/controller/action/variable/value/variable2/value2" Commented Mar 31, 2012 at 20:40
  • Basicly that is what i am doing, just made this to make clear what i want. But thanks for the advice, i am sure others will find it usefull. Commented Mar 31, 2012 at 22:05

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That is working perfectly exactly what i needed. Now my MVC system is fully functional!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.