Laravel如果不创建表';不存在于生产环境中


Laravel create table if doesn't exist on production environment

当环境设置为生产环境时,我需要使用数据库来存储我与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来动态地做到这一点,但不确定这是否是个好主意。