How to access application instance from function helper

I define some functions in helpers, I added to composer.json

"autoload": {
    "classmap": [
        
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "config/helpers.php"
    ]
}

I have some helper function following:

function view($view, $args = []) {
    // but how to access application here?
    return $app->view->render($app->response, $view . '.php',$args);
}

I want to call view function anywhere for render a Twig view, but I can’t access application from global helper function. I tried using debug_backtrace(), but i gues this way is not good for security and performance.

Show me the way, thanks.

Can you show the entire file?

You can pass the $app into the function by using use, if $app is available outsite the function.

function view ($view, $args = []) use ($app)
{
    return $app->view->render($app->response, $view . '.php',$args);
}

But you should use the response instance from the route action, not get a new one the the app!

1 Like