How to use Illuminate Database Query Builder & Eloquent in other framework with PHP 5.3.x

可紊 提交于 2019-12-03 20:26:40

I'm also using Capsule with Slim. First off, make sure that you're using version 4.1.* of Illuminate/Capsule. When 4.2 came out, one of the big changes was that PHP 5.4 became the required minimum. 4.1 will still work with PHP 5.3.

Now, if you've done that and you're still running into problems, this is how I registered capsule with Slim's IoC container:

$app->container->singleton('capsule', function() use ($config) {
    $capsule = new Illuminate\Database\Capsule\Manager;

    $capsule->setFetchMode(PDO::FETCH_OBJ);
    $capsule->addConnection($config['database']);
    $capsule->bootEloquent();

    return $capsule->getConnection();
});

Note the call to getConnection(). This is necessary, as the Capsule global is not getting registered.

Edit: Also note the call to setFetchMode. When using Fluent from within Laravel, queries return instances of stdClass, but the default behavior appears to be to return associative arrays. The framework just overrides that at some point, leading to Capsule behaving in correct, yet unexpected ways. This sets it to run with more expected behavior.

Look at the Laravel datasource connector in PPI 2.1

https://github.com/ppi/framework/tree/2.1/PPI/DataSource/Connection

Using version 4.1 of illuminate/database...simple case with a single connection:

// $app is a Slim instance

// add db connection parameters to the app config using mysql / utf8

$app->config(array(
    'db' => array(
        'driver'    => 'mysql',
        'host'      => 'locahost',
        'database'  => 'mydbname',
        'username'  => 'myuser',
        'password'  => 'mypass',
        'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
        'options'   => array(
            \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
        ),
        'prefix'    => '',
    ),
));

// make sure we always use the same service instance

$app->container->singleton('capsule', function($c) use($app) {
    $capsule = new \Illuminate\Database\Capsule\Manager();
    $capsule->addConnection($params);

    return $capsule;
});

// USE IT ANYWHERE the slim $app instance or the slim app container are visible 

$capsule = $app->capsule;
// ...or if $c is the container
// $capsule = $c->get('capsule');
$people = $capsule->table('person')->take(10)->get();

Alternative easy to use database query builders:

  • doctrine/dbal (btw illuminate/database uses doctrine dbal connection)
  • zendframework/zend-db (providing table data gateway/row data gateway classes as well)
  • j4mie/idiorm
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!