如何创建一个操作实例的辅助函数?

I am busy learning as much as I can about php frameworks.

At the moment I have a file full of routes. The routes take this general form.

$bootstrap->router->add('/home', ['controller' => 'home', 'action' => 'index']);

So, the 'routes' file is not a class, it is just a file which I include into the index.php page just underneath $bootstrap = new Bootstrap($router);.

As you can see, to add a route I add it to the instantiated $bootstrap object, which itself has an instantiated ->router object inside which I am calling the 'add()' method.

Now I want to make it easier to add routes by writing something like this...

route('/home', ['controller' => 'home', 'action' => 'index']);

question

Exactly how to go about this is unclear... I am not even sure if this is a done thing. I have tried making a 'helpers/RoutesHelper file' but that takes my request out of the object scope...

...so I am a bit confused, how do I go about implementing a plane old helper function inside object oriented code?

Many thanks in advance.

anonymous function

If you are willing to add a $ to the beginning of that route(... line:

$route = function($path, $options) use ($bootstrap) {
     $bootstrap->router->add($path, $options);
}

would work.

global $bootstrap

Otherwise it would be dirty to bring the bootstrap object into the route function:

function route($path, $options) {
     global $bootstrap; // <-- i don't like this
     $bootstrap->router->add($path, $options);
}

definitions in array

you could also just make an array in your file like:

$routes = array()
$routes['/home'] = ['controller' => 'home', 'action' => 'index'];
// ... more routes ...

and in your main program just loop over that array:

foreach($routes as $path => $options) {
    $bootstrap->router->add($path, $options);
}

those are the three solutions that pop into my mind ...

Like this

if(!function_exists( 'route' ) ){
    function route( $path, $params ){
        $bootstrap = ''; //?
        $bootstrap->router->add($path, $params);
    }
}

Of course I have no idea where $bootstrap came from, so you'll want that in there, obviously. You could pass that in as a parameter, but it would be better to initialize it inside the function if possible.