Heim  >  Artikel  >  Backend-Entwicklung  >  关于 Laravel Session 的困惑,望高手解决

关于 Laravel Session 的困惑,望高手解决

WBOY
WBOYOriginal
2016-08-26 10:12:54848Durchsuche

在laravel5.*中,session start被放到了web中间件中,如

<code>    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,   // [
            'throttle:60,1',
            'bindings',
        ],
    ];</code>

并且根据Route加载中间件的代码可以得知Controller是在被make之后才调用中间件

<code>    /**
     * Get the middleware for the route's controller.
     *
     * @return array
     */
    public function controllerMiddleware()
    {
        if (! $this->isControllerAction()) {
            return [];
        }

        return ControllerDispatcher::getMiddleware(
            $this->getController(), $this->getControllerMethod()
        );
    }</code>

这个时候问题就来了,我有一个BaseController,在构造函数里面会判断用户登录状态,如果已经登录就获取登录用户信息保存到$this->login_user_info中供子类调用,如果先make controller,session还没有start,因此在构造函数中是无法获取到登录用户的session_id,部分代码如下

<code>/**
 * 控制层公有方法集合
 * Class BaseController
 */
abstract class BaseController extends Controller
{

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public $login_user_info;
    public $login_subuser_info;

    public function __construct()
    {
        $this->userModel    = app(UserModel::class);
        if (session()->get('user_id')) {
            $this->login_user_info          = $this->userModel->getLoginUser();
            //设置模板全局变量
            view()->share(['login_user_info' => $this->login_user_info]);
        }
    }</code>

我测试过在middleware中是可以得到session,因为这个时候已经执行了StartSession中间件代码,至于我为什么要这么做就说来话长,我的项目是一个老项目切换框架到laravel,所以为了最大限度的保持原有逻辑,并且还有一些奇奇怪怪的写法,没有采用Auth,这些暂且不论,有没有办法可以在构造函数中得到session,求各位大神帮忙,谢谢

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn