I don’t exactly understand the difference, but I don’t retrieve the same vars.
First, I’ve followed the 1st method in a ‘Codecourse’ tutorial on youtube. Then I’ve tried to develop Respect-Validation with different languages with the help of this github which basically use the second method with “$this->view->render”
This method helps me to translate my error-form-validation (by getting the vars from languages I load in the controller), but I couldn’t get the vars from the container that is set like that :
$container[‘view’] = function($container){
$view->getEnvironment()->addGlobal(‘auth’, [
‘check’ => $container->auth->check(), // si connecté ou non
‘user’ => $container->auth->user() // id utilisateur
]);
return $view;
};
…And I can’t see in my view if I’m connected or not with “$this->view->render” (I have to reload the page once). If I use “$response->withRedirect”, I don’t get my language datas… :-/
How can I get the advantage of these two redirections methods or how can I change my settings to get all the vars ?
withRedirect will send a HTTP 302 redirect response header to the client (browser). The browser will then redirect the user to the given url. The redirection will happen on the client side (browser).
render just renders the twig template with the given view data and returns a response object. The Browser receives just a standard html page. The response (result) will be displayed as normal page in the browser (client side).
I would not mix templates with business logic like this. Better pass all the required view data in your controller action and not within the container.
Yes. thank you ! For 1), I’ve effectively used Respect/Validation from the page you said.
For 2), I would use session for flash message. But also for the data’s user : When the user signs in, this would be store in session vars ? (for exemple his user-id)
CodeCourse did it completely differently. They make an Auth Class like this :
class Auth{
public function user(){
return User::find($_SESSION['user']);
}
public function check(){
return isset($_SESSION['user']);
}
public function attempt($email, $password){
$user = User::where('email', $email)->first();
if(!$user){return false;}
if(password_verify($password, $user->password)){
$_SESSION['user'] = $user->id;
return true;
}
else{return false;}
}
public function logout(){ unset($_SESSION['user']);}
}
And in the container, they transmit auth vars as global vars :
$container['view'] = function($container){
$view = new \Slim\Views\Twig( __DIR__ . '/../app/Views', ['cache' => false]);
$view->addExtension(new \Slim\Views\TwigExtension( $container->router, $container->request->getUri()));
$view->getEnvironment()->addGlobal('auth', [
'check' => $container->auth->check(), // si connecté ou non
'user' => $container->auth->user() // id utilisateur
]);
$view->getEnvironment()->addGlobal('flash', $container->flash);
return $view;
};