解释如何在构造函数Laravel 5.3中使用Session

时间:2017-01-16 08:19:43

标签: php laravel session laravel-5.3 laravel-middleware

根据laravel docs https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors 我无法再访问构造中的会话,因为中间件尚未加载,它们提供了一个我无法理解的示例

public function __construct()
{
    $this->middleware(function ($request, $next) {
        $this->projects = Auth::user()->projects;

        return $next($request);
    });
}

如何在该功能中访问我的会话? ,解释会做

3 个答案:

答案 0 :(得分:0)

将其放在控制器的__construct()功能中,以处理请求。

答案 1 :(得分:0)

Laravel文档声明您无法在构造函数中访问中间件,因为它尚未加载。

通过使用特定的Closure,你实际上强迫php(和Laravel)在Closure中加载你拥有的任何逻辑作为中间件。看看Laravel提供的basic controller class,看看你是否可以连接点。

基本上,你正在攻击框架。

话虽这么说,这是非常糟糕的做法,你不应该在控制器的构造函数中调整你的会话。

答案 2 :(得分:0)

#include <iostream>
#include <type_traits>

template <typename>
class SmartPtr;

template <typename>
struct isSP : public std::false_type
 { };

template <typename P>
struct isSP<SmartPtr<P>> : public std::true_type
 { };

template<class Pointee>
class SmartPtr {
private:
    Pointee* _pointee;
    SmartPtr(SmartPtr &);
public:
    explicit SmartPtr(Pointee * pt = 0);
    ~SmartPtr();
    SmartPtr& operator=(SmartPtr&);
    operator Pointee*() const { return _pointee; }
    bool operator!() const { return _pointee != 0; }
    bool defined() const { return _pointee != 0; }


    auto const getPtr (std::true_type const &) const 
     { return _pointee->operator->(); }

    auto const getPtr (std::false_type const &) const 
     { return _pointee; }

    auto const operator->() const
     { return getPtr(isSP<Pointee>{}); }


    Pointee& operator*() const { return *_pointee; }
    Pointee* get() const { return _pointee; }
    Pointee* release();
    void reset(Pointee * pt = 0);
};

template<class Pointee>
SmartPtr<Pointee>::SmartPtr(SmartPtr &spt) :_pointee(spt.release()) {
    return;
}

template<class Pointee>
SmartPtr<Pointee>::SmartPtr(Pointee * pt) : _pointee(pt) {
    return;
}

template<class Pointee>
SmartPtr<Pointee>::~SmartPtr() {
    delete _pointee;
}

template<class Pointee>
SmartPtr<Pointee>& SmartPtr<Pointee>::operator=(SmartPtr &source)
{
    if (&source != this)
        reset(source.release());
    return *this;
}

template<class Pointee>
Pointee * SmartPtr<Pointee>::release() {
    Pointee* oldSmartPtr = _pointee;
    _pointee = 0;
    return oldSmartPtr;
}

template<class Pointee>
void SmartPtr<Pointee>::reset(Pointee * pt) {
    if (_pointee != pt)
    {
        delete _pointee;
        _pointee = pt;
    }
    return;
}


struct Time
 {
   int a, b, c;

   Time (int a0, int b0, int c0) : a{a0}, b{b0}, c{c0}
    { }

   int hours () const
    { return a; }
 };


int main ()
 {
   SmartPtr<SmartPtr<SmartPtr<Time>>>
      sp3(new SmartPtr<SmartPtr<Time>>(new SmartPtr<Time>(new Time(0, 0, 1))));

   std::cout << sp3->hours() << std::endl;    
 }

此代码用于根据会话更改语言我使用laravel 5.5的版本注意:你必须先调用middelware然后使用session作为构造函数而不是看到session这对我有用