Doubt in the Middleware Before of the Silex Controllerprovider

Asked

Viewed 261 times

0

Opa to all of you, 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;
}

}

Just that part of Middleware Before at the beginning of the class repeats itself at all and I would like to know how I can isolate this part of the code into 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

2 answers

1

I think if you do that it solves.

// 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());

So all controllers using mount used the same before.

  • good? Look this way you quoted I apply before to all project controllers, but in fact I only need in the administrative area where I created a controller with the name $admin, $Adm = $app['controllers_factory'];. My question is this how I apply only to this particular controller. Thank you

0

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.