在会话中存储对象 Symfony 2 [英] Store objects in sessions Symfony 2

查看:23
本文介绍了在会话中存储对象 Symfony 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Symfony 2 编写一个小型电子商店应用程序,我需要某种方式在会话中存储用户的购物车.我认为使用数据库不是一个好主意.

I am writing a small e-shop application with Symfony 2 and I need some way to store the user's shopping cart in a session. I think using a database is not a good idea.

应用程序将使用诸如 ProductCategoryShoppingCart 之类的实体,其中 Product 和 Category 被持久化到数据库中,用户将选择产品进入他们的购物车.

The application will use entities like Product, Category, ShoppingCart where Product and Category are persisted into the database and users will be choosing products into their ShoppingCart.

我发现了 NativeSessionStorage 类,它应该将实体保存到会话中.但是没有书面的应用程序实现过程.

I have found NativeSessionStorage class which is supposed to save an entity into a session. But there is no written process of implementation into an application.

我是在控制器中还是在单独的类 ShoppingCart 中使用它?你能给我一个 NativeSessionStorage 用法的简短例子吗?

Do I use this in the controller or in a separated class ShoppingCart? Could you give me a short example of NativeSessionStorage usage?

问题设置不正确:

目标不是将所有产品 ID 保存到 cookie 中.目标是在服务器端的应用程序内存中只保存一个篮子(装满产品)的参考,并为用户分配适当的篮子.这甚至可以在 PHP 中执行此操作吗?

The goal is not to save all product ids into a cookie. The goal is to save only a reference for basket (filled with products) in application memory on server-side and assign proper basket to user. Is this even possible to do this in PHP?

EDIT2:

使用服务是更好的解决方案吗?

Is a better solution to use a service?

推荐答案

不知道这种方式是否是临时存储数据的更好方式.您可以使用它来实例化会话对象:

Don't know if this way is the better way to store your data temporary. You can use this to instantiate a session object :

$session = $this->get("session");

不要忘记控制器中的使用":

Don't forget the 'use' in your controller :

use Symfony\Component\HttpFoundation\Session;

然后,当您想设置如下变量时,会话会自动启动:

Then, the session starts automatically when you want to set a variable like :

$session->set("product name","computer");

这是基于 Session 的使用类,通俗易懂.常用定义:

This is based on the use of the Session class, easy to understand. Commonly definitions :

get(string $name, mixed $default = null)

Returns an attribute.

set(string $name, mixed $value)

Sets an attribute.

has(string $name)

Checks if an attribute is defined.

另外,看看存储数据的其他方式:多会话存储

Also, take a look to the other ways to store your data : Multiple SessionStorage

这篇关于在会话中存储对象 Symfony 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆