Issue
Hello I am trying to learn how to use symfony so I came up with an idea to make a page that shows a number that is incremented every time page refreshes. I also wanted not to use database so exercise was not so easy. I've tried to make a service that holds variable and increments it, but because of my poor understanding of symfony it didn't work :( Then I have tried to use session but the result was the same :(( and I ran out of ideas. What I have done until now:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Addition\GlobalKeeper;
/**
* Class counterController
* @package App\Controller
* @Route("/")
*/
class counterController extends AbstractController
{
private $Gcounter;
public function __construct()
{
$this->Gcounter = new GlobalKeeper();
}
/**
* @Route("/")
*/
public function Counter (){
$this->Gcounter->startfordummy();
$this->Gcounter->increment();
return $this->render('home\insides.html.twig',
[ 'num' => $this->Gcounter->getCounter()]);
}
}
/////
<?php
namespace App\Addition;
use Symfony\Component\HttpFoundation\Session\Session;
class GlobalKeeper
{
public $session;
public function __constructor(){
$session = new Session();
$session->start();
if(null !==$session->get("test")) $session->set("test",0);
}
public function startfordummy(){
$session = new Session();
$session->start();
if(null !==$session->get("test")) $session->set("test",0);
}
public function getCounter()
{
return $this->session->get("test");
}
public function increment()
{
$this->session->set("test", $session->get("test") + 1);
}
}
also this code results in Call to a member function set() on null
Solution
The docs are a terrible thing to waste.
class DefaultController extends AbstractController
{
/**
* @Route("/counter", name="counter")
*/
public function counter(SessionInterface $session)
{
$counter = $session->has('counter') ? (int)$session->get('counter') : 0;
$counter++;
$session->set('counter',$counter);
return $this->render('default/counter.html.twig', [
'counter' => $counter,
]);
}
}
Tell your instructor that they are not only doing a terrible job of teaching you about sessions but also about how to search for information.
Answered By - Cerad
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.