Search code examples
phpsymfonyroutessilex

how to include functions within all Silex routes DRY / global?


I want to include a file and a variable within all my routes e.g.

$app->get('/', function() use ($app) {

$auth='code';
require __DIR__.'/assets/helpers.php';

....

});

$app->get('login', function() use ($app) {

$auth='code';    
require __DIR__.'/assets/helpers.php';

....

});

I need to repeat the code on every route declaration. Putting the variable or redirect at the top of the file does not include it within the $app scope, even when setting global $auth;


Solution

  • This is probably best accomplished with route middleware:

    use Silex\Application;
    use Symfony\Component\HttpFoundation\Request;
    
    $app = new Application();
    
    $setup = function (Request $request) use ($app) {
        $auth='code';
        require __DIR__.'/assets/helpers.php';
    };
    
    $app->get('/', function() use ($app) {})
        ->before($setup);
    
    $app->get('/login', function() use ($app) {})
        ->before($setup);
    

    The only thing I am not sure of here is if this will cause scope issues for you. For example if you helpers depend on some other variable that might be established inside your controller closure then that might not work. But at that point I think it's kind of a bad smell in design and you should probably be abstracting those things into Service Providers.