当环境设置为生产环境时,我需要使用数据库来存储我与Laravel 4的会话。如果是本地文件,则可以使用标准文件驱动器系统。
我无法访问命令行,因此无法运行任何迁移、手工命令(CloudFoundry设置)。所以我的想法是在我的app/start/global.php
文件中添加一个检查:
if (App::environment('production'))
{
if(! Schema::hasTable( Config::get('session.table') )) {
Schema::create( Config::get('session.table'), function($table)
{
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
});
}
}
如果它当前处于生产模式(此位有效),请检查是否有一个表的名称在我的app/config/session.php
文件中定义。如果没有,则使用给定的名称创建此表。我注意到来自api的hasTable
(http://laravel.com/api/4.1/Illuminate/Database/Schema/Builder.html#method_hasTable)。
然而,当我的应用程序加载时,我会收到错误:
RuntimeException: PDOException was thrown when trying to read the session data: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'table_name.sessions' doesn't exist
这是因为应用程序的生命周期吗?否则我怎么能这么做。。。
您不能执行此操作,因为会话在加载global.php
文件之前启动。更具描述性的是,会话在handle
方法中的Illuminate'Session'Middleware
文件中启动,在handle
方法中,您可以看到:
if ($this->sessionConfigured())
{
$session = $this->startSession($request);
$request->setSession($session);
}
这发生在框架的引导过程中,之后调用$app->booted
,其中包括global.php
文件:
// Inside booted handler
$path = $app['path'].'/start/global.php';
if (file_exists($path)) require $path;
因此,在调用Illuminate'Session'Middleware'handle
之前需要session table
。您应该手动创建一个table
,如果环境是生产环境,那么将使用该表,否则将不会使用它。那么,如果你总是在database
中保留一张桌子,会有什么问题呢?
我也在想,也许你可以创建一个自定义的middleware
来动态地做到这一点,但不确定这是否是个好主意。