2015-02-07 157 views
0

我刚刚在laravel中创建了一个库类。Laravel库处理消息

class Message { 

    public static $data = array(); 

    public function __construct() { 
     // If session has flash data then set it to the data property 
     if (Session::has('_messages')) { 
      self::$data = Session::flash('_messages'); 
     } 
    } 

    public static function set($type, $message, $flash = false) { 
     $data = array(); 

     // Set the message properties to array 
     $data['type'] = $type; 
     $data['message'] = $message; 

     // If the message is a flash message 
     if ($flash == true) { 
      Session::flash('_messages', $data); 
     } else { 
      self::$data = $data; 
     } 
    } 

    public static function get() { 
     // If the data property is set 
     if (count(self::$data)) { 
      $data = self::$data; 



      // Get the correct view for the message type 
      if ($data['type'] == 'success') { 
       $view = 'success'; 
      } elseif ($data['type'] == 'info') { 
       $view = 'info'; 
      } elseif ($data['type'] == 'warning') { 
       $view = 'warning'; 
      } elseif ($data['type'] == 'danger') { 
       $view = 'danger'; 
      } else { 
       // Default view 
       $view = 'info'; 
      } 

      // Return the view 
      $content['body'] = $data['message']; 
      return View::make("alerts.{$view}", $content); 
     } 
    } 
} 

我可以在我的视图中使用这个类,调用Message :: get()。在控制器中,我可以将消息设置为Message :: set('info','here message here');它工作得很好。

但是,我不能使用此类用于使用Message :: set('info','success message here。',true)重定向的Flash消息。任何想法,这个代码有什么不对?

+0

是的。正常情况下会从会话中检索闪烁的数据。使用'Session :: get('_ messages');' – lukasgeiter 2015-02-07 13:35:47

回答

0

第一个问题是当使用上面的get和set方法时,不调用构造函数,只需稍作修改即可使用代码。 :)

class Message { 

    public static $data = array(); 

    public static function set($type, $message, $flash = false) { 
     $data = array(); 

     // Set the message properties to array 
     $data['type'] = $type; 
     $data['message'] = $message; 

     // If the message is a flash message 
     if ($flash == true) { 
      Session::flash('_messages', $data); 
     } else { 
      self::$data = $data; 
     } 
    } 

    public static function get() { 

     // Check the session if message is available in session 
     if (Session::has('_messages')) { 
      self::$data = Session::get('_messages'); 
     } 

     // If the data property is set 
     if (count(self::$data)) { 
      $data = self::$data; 

      // Get the correct view for the message type 
      if ($data['type'] == 'success') { 
       $view = 'success'; 
      } elseif ($data['type'] == 'info') { 
       $view = 'info'; 
      } elseif ($data['type'] == 'warning') { 
       $view = 'warning'; 
      } elseif ($data['type'] == 'danger') { 
       $view = 'danger'; 
      } else { 
       // Default view 
       $view = 'info'; 
      } 

      // Return the view 
      $content['body'] = $data['message']; 
      return View::make("alerts.{$view}", $content); 
     } 
    } 
}