Working with Silex sessions

5

Good evening,

I have a question on how to add, change, and delete data in the Silex Session. His API documentation is very simple and unexplained.

It is the following:

I need to create a session containing an array of values I did so to create it:

$app['session']->set('container',['nome'=>'fulano', 'idade'=>21]);

Now the doubts begin.

1- How do I add more values in this session? Ex. City = > São Paulo

2- How do I change for example the age from 21 to 30?

3- How do I delete something? ex: name

4- How do I test if the key is created? Ex: If I want to test if the age key is set.

Thank you

    
asked by anonymous 06.02.2015 / 00:08

1 answer

3

After installing Silex and reading some articles about Symfony 2 , I came to a nice conclusion.

By default, only Symfony 2 can be included in the chave/valor .

It's like it's meant to be used like this:

$app['session']->set('nome', 'Wallace');
$app['session']->set('idade', '24 anos');

But through a class called Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag , which is present in the vendor folder (which is part of Silex pendencies), we can use Session similarly to Namespace of PHP. >

See test that I performed as an example:

include_once 'vendor/autoload.php';

use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;

$app = new Silex\Application();

$app->register(new Silex\Provider\SessionServiceProvider());

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

    // defino o valor que será utilizado como namespace
    $bag = new NamespacedAttributeBag('container');
    // adicionamos a instância da Bag    
    $app['session']->registerBag($bag);


    // definimos os valores do container
    $app['session']->set('container/nome', 'Wallace');
    $app['session']->set('container/idade', '24 anos');

    $data = $app['session']->get('container');

    var_dump($data); 
   //Resultado: array(2) { ["nome"]=> string(7) "Wallace" ["idade"]=> string(7) "24 anos" }


    return '';
});

$app->run();

That is:

$app['session']->set('container/nome', 'wallace');

is the same as:

$_SESSION['container']['nome'] = 'Wallace';

To end the day, I hope this helps!

Answers

  

1- How do I add more values in this session? Ex. City = > São Paulo

$app['session']->set('container/cidade', 'São Paulo');
  

2- How do I change for example the age from 21 to 30?

$app['session']->set('container/idade', '21');
echo $app['session']->get('container/idade'); // 21
$app['session']->set('container/idade', '30'); // define um novo valor
  

3- How do I delete something? ex: name

$app['session']->remove('container/nome');
  

4- How do I test if the key is created? Ex: If I want to test if the age key is set.

var_dump($app['session']->has('container/idade'))

And finally, to access the array with all the data

var_dump($app['session']->get('container'));
    
06.02.2015 / 02:57