我可以在 Laravel 5 会话中保存对象、对象集合吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29237399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:12:21  来源:igfitidea点击:

Can I save Objects, Object Collections in a Laravel 5 Session?

phpobjectlaravelsavesession-variables

提问by fefe

Is it possible to save php Objects, object collections in laravel 5 Session?

是否可以在 Laravel 5 Session 中保存 php 对象、对象集合?

I was trying but I get error on this

我正在尝试,但在这方面出现错误

Serialization of 'Closure' is not allowed vendor/illuminate/session/Store.php line 255

Session::put('my_php_object', $obj );
Session::save();


public function onRun()
{

    $this->addCss('assets/css/custom.css');
    $this->socialite_providers = $this->page['socialite_providers'] =$this->providersList();

    //check for provider param in url
    if($provider = $this->param('provider')){

        $this->setSessionProvider($provider);
        $this->provider = $provider;
        $this->callback_url = preg_replace('~.*\K:(.*)~s','',Request::root().$this->page->url);
        $this->request = $this->createRequest($provider);


        Session::save();
        return $this->request->redirect();

    }

    //Authorize user if Request has code
    if(Request::has('code')){

        if(!$this->getSession())
            return;

        //reuse save session

    }

}

public function createRequest($provider)
{
    $instance = Socialite::driver($provider);
    $init = $this->injectCredentials($instance, $provider);

    $this->setSession($init);
    return $init;
}

public function injectCredentials($instance, $provider){
    $credential = $this->providerData($provider)->toArray();
    $instance = new $instance
    (
        Request::instance(),
        $credential['client_id'],
        $credential['client_secret'],
        $this->callback_url
    );

    return $instance;
}

public function setSession($init)
{
    if(Session::has('socialite_object'))
        Session::forget('socialite_object');


    Session::put('socialite_object', $init );

}

回答by Martin Rifon

You could always store the JSON representation of the object you tried to store.

您始终可以存储您尝试存储的对象的 JSON 表示。

However, I've heard it's generally a good idea not to store large things in the Session, is there anyway you could manage by storing something else? If you are storing an object from the DB, you could store the Id and recover the object with a query.

但是,我听说不要在 Session 中存储大的东西通常是个好主意,无论如何你可以通过存储其他东西来管理?如果您要存储来自数据库的对象,则可以存储 Id 并通过查询恢复该对象。