puiu91
6/20/2016 - 12:01 AM

PHP Registering and Calling Callbacks

PHP Registering and Calling Callbacks

<?php

require 'Router.php';
require 'Output.php';

$router = new Router();
$router->route('/^\/blog\/(\w+)\/(\d+)\/?$/', function($category, $id) {

    $OutputObject = new Output();
    $OutputObject::test();

    print 'category= ' . $category . ', id= ' . $id;
 });

$router->execute($_SERVER['REQUEST_URI']);
<?php

class Router {

    private $routes = array();

    public function route($pattern, $callback) {
        $this->routes[$pattern] = $callback;
    }

    public function execute($uri) {

        echo '<pre>';
        print_r($this->routes);
        echo '</pre>';

        foreach ($this->routes as $pattern => $callback) {
            if (preg_match($pattern, $uri, $params) === 1) {
                array_shift($params);

                echo '<pre>';
                print_r($callback);
                echo '</pre>';

                // call the function
                return $callback('one', 'two');

                // return call_user_func($callback, 'ff', 'two');

                // return call_user_func_array($callback, ['one','two']);
            }
        }
    }

}
<?php

class Output {
  public function __construct() {
    echo 'INSIDE OF OUTPUT CLASS OBJECT';
  }

  public static function test() {
    echo 'this is a test';
  }
}