database.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php namespace Laravel\Session;
  2. use Laravel\Database\Connection;
  3. class Database extends Driver implements Sweeper {
  4. /**
  5. * The database connection.
  6. *
  7. * @var Connection
  8. */
  9. protected $connection;
  10. /**
  11. * The database table to which the sessions should be written.
  12. *
  13. * @var string
  14. */
  15. protected $table;
  16. /**
  17. * Create a new database session driver.
  18. *
  19. * @param Connection $connection
  20. * @param string $table
  21. * @return void
  22. */
  23. public function __construct(Connection $connection, $table)
  24. {
  25. $this->table = $table;
  26. $this->connection = $connection;
  27. }
  28. /**
  29. * Load a session by ID.
  30. *
  31. * @param string $id
  32. * @return array
  33. */
  34. protected function load($id)
  35. {
  36. $session = $this->table()->find($id);
  37. if ( ! is_null($session))
  38. {
  39. return array(
  40. 'id' => $session->id,
  41. 'last_activity' => $session->last_activity,
  42. 'data' => unserialize($session->data)
  43. );
  44. }
  45. }
  46. /**
  47. * Save the session to persistant storage.
  48. *
  49. * @return void
  50. */
  51. protected function save()
  52. {
  53. $this->delete($this->session['id']);
  54. $this->table()->insert(array(
  55. 'id' => $this->session['id'],
  56. 'last_activity' => $this->session['last_activity'],
  57. 'data' => serialize($this->session['data'])
  58. ));
  59. }
  60. /**
  61. * Delete the session from persistant storage.
  62. *
  63. * @return void
  64. */
  65. protected function delete()
  66. {
  67. $this->table()->delete($this->session['id']);
  68. }
  69. /**
  70. * Delete all expired sessions from persistant storage.
  71. *
  72. * @param int $expiration
  73. * @return void
  74. */
  75. public function sweep($expiration)
  76. {
  77. $this->table()->where('last_activity', '<', $expiration)->delete();
  78. }
  79. /**
  80. * Get a session database query.
  81. *
  82. * @return Query
  83. */
  84. protected function table()
  85. {
  86. return $this->connection->table($this->table);
  87. }
  88. }