Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active May 1, 2020 02:46
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ziadoz/7326872 to your computer and use it in GitHub Desktop.
Save ziadoz/7326872 to your computer and use it in GitHub Desktop.
Laravel Eloquent/Capsule Silex Service Provicer
<?php
$app = new Silex\Application;
$app->register(new CapsuleServiceProvider, array(
// DB Connection: Multiple.
'capsule.connections' => array(
'default' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'dname1',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'logging' => false, // Toggle query logging on this connection.
),
'other' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'dbname2',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'logging' => true, // Toggle query logging on this connection.
),
),
/*
// DB Connection: Single.
'capsule.connection' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'dbname',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'logging' => true, // Toggle query logging on this connection.
),
*/
// Cache.
'capsule.cache' => array(
'driver' => 'apc',
'prefix' => 'laravel',
),
/*
// Cache: Available Options.
'capsule.cache' => array(
'driver' => 'file',
'path' => '/path/to/cache',
'connection' => null,
'table' => 'cache',
'memcached' => array(
array(
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 100
),
),
'prefix' => 'laravel',
),
*/
/*
Other Options:
'capsule.global' => true, // Enable global access to Capsule query builder.
'capsule.eloquent' => true, // Automatically boot Eloquent ORM.
*/
));
$app['capsule']; // Establish database connection manually (otherwise this occurs upon $app->run()).
// Create an Eloquent Model.
class Book extends Illuminate\Database\Eloquent\Model
{
protected $table = 'books';
}
// Work with the Eloquent Model.
$book = new Book;
$book->title = '61 Hours';
$book->author = 'Lee Child';
$book->save();
$book = Book::find(1);
print_r($book);
// Use the Capsule query builder globally.
use Illuminate\Database\Capsule\Manager as Capsule;
$book = Capsule::table('books')->where('id', 1)->get();
print_r($book);
$app->run(); // Database connection established automatically upon Silex run.
<?php
use Silex\Application;
use Silex\ServiceProviderInterface;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
use Illuminate\Cache\CacheManager;
class CapsuleServiceProvider implements ServiceProviderInterface
{
/**
* Register the Capsule service.
* See: http://stackoverflow.com/questions/17105829/using-eloquent-orm-from-laravel-4-outside-of-laravel
*
* @param Silex\Application $app
**/
public function register(Application $app)
{
$app['capsule.connection_defaults'] = array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => null,
'username' => 'root',
'password' => null,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => null,
'logging' => false,
);
$app['capsule.global'] = true;
$app['capsule.eloquent'] = true;
$app['capsule.container'] = $app->share(function() {
return new Container;
});
$app['capsule.dispatcher'] = $app->share(function() use($app) {
return new Dispatcher($app['capsule.container']);
});
if (class_exists('Illuminate\Cache\CacheManager')) {
$app['capsule.cache_manager'] = $app->share(function() use($app) {
return new CacheManager($app['capsule.container']);
});
}
$app['capsule'] = $app->share(function($app) {
$capsule = new Capsule($app['capsule.container']);
$capsule->setEventDispatcher($app['capsule.dispatcher']);
if (isset($app['capsule.cache_manager']) && isset($app['capsule.cache'])) {
$capsule->setCacheManager($app['capsule.cache_manager']);
foreach ($app['capsule.cache'] as $key => $value) {
$app['capsule.container']->offsetGet('config')->offsetSet('cache.' . $key, $value);
}
}
if ($app['capsule.global']) {
$capsule->setAsGlobal();
}
if ($app['capsule.eloquent']) {
$capsule->bootEloquent();
}
if (! isset($app['capsule.connections'])) {
$app['capsule.connections'] = array(
'default' => (isset($app['capsule.connection']) ? $app['capsule.connection'] : array()),
);
}
foreach ($app['capsule.connections'] as $connection => $options) {
$options = array_replace($app['capsule.connection_defaults'], $options);
$logging = $options['logging'];
unset($options['logging']);
$capsule->addConnection($options, $connection);
if ($logging) {
$capsule->connection($connection)->enableQueryLog();
} else {
$capsule->connection($connection)->disableQueryLog();
}
}
return $capsule;
});
}
/**
* Boot the Capsule service.
*
* @param Silex\Application $app;
**/
public function boot(Application $app)
{
if ($app['capsule.eloquent']) {
$app->before(function() use($app) {
$app['capsule'];
}, Application::EARLY_EVENT);
}
}
}
@miguelsaddress
Copy link

Hello, thank you very much for the provider :) I am totally new to Silex and to Eloquent... I am having an issue that I don't know if its related to something of the gist:

My index.php is more or less:

<?php
//require of the vendor autoload.php
//and require of CapsuleServiceProvider, etc
use Illuminate\Database\Eloquent\Model as Eloquent;

$app = new Silex\Application();
$app->register(new CapsuleServiceProvider, array(

    // DB Connection: Single.
    'capsule.connection' => array(
        'driver'    => 'mysql',
        'host'      => 'dev-3.local',
        'database'  => 'localhost',
        'username'  => 'username',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

));

class Companies extends Eloquent{
    protected $table = "t_companies";
}

var_dump( Companies::find(1066) );
die;

But for some reason it does not connect but the DB values for the connection are right and I can use those values to connect via other apps or console.

The error

Fatal error: Call to a member function connection() on a non-object in /Users/Miguel/Desktop/testSilex/vendor/illuminate/database/Illuminate/Database/Eloquent/Model.php on line 2787

Did this happen to you? any idea?

Thank you again!

@miguelsaddress
Copy link

PD: Excuse my ignorance.
It seems the intended use of this provider is to use the "QueryBuilder" feature

$company = $capsule::table('t_companies')->where('id', 1066)->get();

So i guess that, if i try to use Eloquent as having Models, I would have to do the set up as it says at the provided link:
http://stackoverflow.com/questions/17105829/using-eloquent-orm-from-laravel-4-outside-of-laravel

Am i wrong?

thank you!

@ziadoz
Copy link
Author

ziadoz commented Aug 20, 2014

@miguelsaddress Sorry it's taken me so long to reply, Github doesn't appear to show notifications for comments on gists.

A connection to the database is only established once Silex is booted, which happens when you call $app->run(). If you need to establish the connection manually before then, you'll need to call $app['capsule']; in your code before you start working with your models:

<?php
require __DIR__ . '/vendor/autoload.php';

$app = new Silex\Application();
$app->register(new CapsuleServiceProvider, array(
    'capsule.connection' => array(
        'driver'    => 'mysql',
        'host'      => 'dev-3.local',
        'database'  => 'localhost',
        'username'  => 'username',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    )
));

$app['capsule'];

class Companies extends Illuminate\Database\Eloquent\Model 
{
    protected $table = "t_companies";
}

var_dump(Companies::find(1066));

By default you can access the Capsule query builder globally. This is controlled by the capsule.global` option:

<?php
require __DIR__ . '/vendor/autoload.php';

$app = new Silex\Application();
$app->register(new CapsuleServiceProvider, array(
    'capsule.global' => true,
    'capsule.connection' => array(
        // connection details.
    )
));

Capsule::table('t_companies')->where('id', 1066)->get();

Hopefully this makes sense.

@ziadoz
Copy link
Author

ziadoz commented Aug 20, 2014

I've updated the service provider so it now works correctly with the latest version of Pimple by removing all references to $app->share(). I've also added a new parameter called logging that allows per-connection control of query logging. Finally, I've updated the app.php script with some better examples.

@gvsrepins
Copy link

Thank you very much, this is very insightful!

@ziadoz
Copy link
Author

ziadoz commented Oct 16, 2014

I've added back $app->share() so that things work correctly, as the latest version of Silex isn't using Pimple 3.0 yet.

@ziadoz
Copy link
Author

ziadoz commented Mar 15, 2015

This project now has a permanent home on Github: https://github.com/ziadoz/silex-capsule

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment