Doubts in the Middleware Before of the Silex ControllerProvider

0

Oops, everyone, Personal I have several classes that follow this structure:

class TestController implements ControllerProviderInterface {

public function connect(Application $app)
{
    $adm = $app['controllers_factory'];
    $adm->before(function() use($app){
        $login=new \JN\Core\Login($app);

        if($login::verificaLogin()['status']==true){
            $app['twig']->addGlobal('login', $login);                
        }else{
            return $app->redirect($app["url_generator"]->generate("adminLogin"));
        }
    });

    $adm->get('/ola', function() use($app) {
        $valores = $app['userService']->listarTudo();
        $passagem = [
            'tituloPagina'=>'Teste',
            'erros'=> ''
        ];
        return $app['twig']->render('/admin/abertura.twig', ['passagem'=>$passagem]);
    });

    return $adm;
}

}

So the middleware part at the beginning of the class repeats at all and I would like to know how I can isolate this part of the code in another class and inject it into the classes I need this Middleware. Code to be removed and then injected:

$adm->before(function() use($app){
        $login=new \JN\Core\Login($app);

        if($login::verificaLogin()['status']==true){
            $app['twig']->addGlobal('login', $login);

        }else{
            return $app->redirect($app["url_generator"]->generate("adminLogin"));
        }
    });

In the index.php file I mount the routes like this:

$app->mount('/blog', new \JN\Controller\Admin\TestController());

Thank you

    
asked by anonymous 13.02.2015 / 00:25

2 answers

1

I think if you do that it will work.

// index.php
$app->before(function() use($app){
        $login=new \JN\Core\Login($app);

        if($login::verificaLogin()['status']==true){
            $app['twig']->addGlobal('login', $login);

        }else{
            return $app->redirect($app["url_generator"]->generate("adminLogin"));
        }
    });

$app->mount('/blog', new \JN\Controller\Admin\TestController());

In this way all controllers that use mount used the same before.

    
26.03.2015 / 19:56
0

You can create a separate middleware (before, after of finish) attribute and inject directly into the desired route / controller. So:

$before = function (Request $request, Application $app) {
    // ...
};

$app->mount('/blog', new \JN\Controller\Admin\TestController())
->before($before);
    
30.09.2016 / 21:49