简体   繁体   English

我应该在Laravel 5.7中更好地使用session()或collect()辅助函数吗?

[英]Should I better use session() or collect() helper function in Laravel 5.7?

I have stored my array data in the session as following. 我将我的数组数据存储在会话中,如下所示。

session(['my_key' => ['car' => 123, 'motor' => 45, 'boat' => 678]]);

To get the keys I could do the following: 要获取密钥,我可以执行以下操作:

$car_key = session('my_key.car');
$motor_key = session('my_key.motor');
$boat_key = session('my_key.boat');

Or I can do the following: 或者我可以执行以下操作:

$my_keys = session('my_key');

$car_key = collect($my_keys)->get('car');
$motor_key = collect($my_keys)->get('motor');
$boat_key = collect($my_keys)->get('boat');

I don't know how session() and collect()->get() function handle array . 我不知道session()collect()->get()函数如何处理array Is one approach better than another in this case? 在这种情况下,一种方法是否比另一种更好? Or it does not matter that much, even the session stores array with large data? 还是没关系,甚至会话都可以存储具有大数据的数组?

collect() helper is used to create a collection. collect() helper用于创建一个集合。 In you second way you create three different collections, containg the same collection data. 第二种方法是创建三个不同的集合,其中包含相同的集合数据。 And then you get the data, by the key from each collection. 然后,通过每个集合的键获取数据。 The colde seems to be redudant and is not used as it should be used. 该冷汁似乎是多余的,没有被使用,应该使用。

Use the session() helper 使用session()助手

It depends. 这取决于。

If you want to use methods that are only available on collections then that would be a perfectly valid way to do so. 如果要使用仅在集合上可用的方法,那么这将是一种完全有效的方法。 A simpler approach would be to use: 一个更简单的方法是使用:

$myCollection = collect(session('my_key'));

That way you can just use $myCollection->get('car') etc, rather than creating multiple collections. 这样,您可以只使用$myCollection->get('car')等,而不用创建多个集合。

If however you just want to retrieve the value and are happy with an array you can just use the session() helper and return the data as normal. 但是,如果您只想检索该值并对数组满意,则可以使用session()帮助器并正常返回数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM