protected function setValidator() { $filesystem = new FileLoader(new Filesystem(), CONFIG_DIR . DIRECTORY_SEPARATOR . 'langs'); $translator = new Translator($filesystem, Main::$app->web->get('locale', false) ?: 'en'); $this->validator = new ValidatorFactory($translator); $verifier = new DatabasePresenceVerifier($this->capsule->getDatabaseManager()); $this->validator->setPresenceVerifier($verifier); }
/** * Initializes the Eloquent ORM. */ public function initialize() { $this->capsule->bootEloquent(); if ('default' !== $this->defaultConnection) { $this->capsule->getDatabaseManager()->setDefaultConnection($this->defaultConnection); } }
public function register() { $this->app->singleton('laravel.db', function ($app) { $config = $app['config']; // Get the default database from the configuration $default = $config['database.default']; // Create an capsule instance $capsule = new CapsuleManager($app); // Override the default value with the user's config value $config['database.default'] = $default; if (!isset($config['database.connections']) || empty($config['database.connections'])) { throw new ConfigurationException("Invalid database configuration"); } $connections = $config['database.connections']; foreach ($connections as $name => $connectionConfig) { $capsule->addConnection($connectionConfig, $name); } $capsule->setAsGlobal(); // Setup the Eloquent ORM... if ($config['eloquent.boot'] === true) { $capsule->bootEloquent(); } return $capsule->getDatabaseManager(); }); }
/** * @param $config * @return \Illuminate\Database\ConnectionResolverInterface */ protected function getConnectionResolver($config) { $name = $config['database.default']; $conn = $config['database.connections'][$name]; $db = new Manager(); $db->addConnection($conn); return $db->getDatabaseManager(); }
public function setUp() { $this->fileSystem = new Filesystem(); $this->cache = new Repository(new FileStore($this->fileSystem, './cache')); $this->fileSystem->copy('./stubs.sqlite', './stubs-real.sqlite'); $capsule = new Capsule(); $capsule->addConnection(['driver' => 'sqlite', 'database' => './stubs-real.sqlite', 'prefix' => '']); $capsule->setAsGlobal(); $capsule->bootEloquent(); $this->connection = $capsule->getDatabaseManager()->connection('default'); }
protected function initDb() { $capsule = new Manager(); $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', 'fetch' => PDO::FETCH_CLASS]); $capsule->getConnection()->setFetchMode(PDO::FETCH_CLASS); $capsule->setAsGlobal(); $capsule->bootEloquent(); $this->db = $capsule->getDatabaseManager(); $this->createTables(); $this->initMuffing(); return $this->db; }
/** * Start up eloquent * * @param array|null $credentials * * @return \Illuminate\Database\Connection|null */ public function connect(array $credentials = null) { if ($credentials = $credentials ?? $this->getDsn()) { $this->capsule->getDatabaseManager()->purge($this->capsule->getDatabaseManager()->getDefaultConnection()); $this->capsule->addConnection(array_merge(['driver' => 'mysql', 'host' => 'localhost', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => ''], $credentials)); $this->capsule->setEventDispatcher($this->dispatcher); $this->capsule->setAsGlobal(); $this->capsule->bootEloquent(); $this->connection = $this->capsule->getConnection(); $this->connection->enableQueryLog(); return $this->connection; } return null; }
/** * Set up the tests */ public static function setUpBeforeClass() { $capsule = new Manager(); $capsule->addConnection(array('driver' => 'sqlite', 'database' => ':memory:')); // Bind to Eloquent $capsule->setAsGlobal(); $capsule->bootEloquent(); // Set facades DB::setFacadeApplication(new Container()); DB::swap($capsule->getDatabaseManager()); // Reguard attributes Model::reguard(); self::createTables($capsule); }
/** * Register database services * * @param PimpleContainer $di Container */ public function register(PimpleContainer $di) { $params = $this->databaseParams; $di['dbConnection'] = function () use($params, $di) { $capsule = $di['db']; return $capsule->getConnection(); }; $di['dbConnectionResolver'] = function () use($params, $di) { $connection = $di['dbConnection']; $resolver = new ConnectionResolver(['default' => $connection]); $resolver->setDefaultConnection('default'); return $resolver; }; $di['dbMigrationRepository'] = function () use($params, $di) { $resolver = $di['dbConnectionResolver']; $repository = new DatabaseMigrationRepository($resolver, 'migrations'); return $repository; }; $di['dbMigrator'] = function () use($params, $di) { class_alias(Schema::class, 'Schema'); Schema::setContainer($di); $resolver = $di['dbConnectionResolver']; $repository = $di['dbMigrationRepository']; $filesystem = new Filesystem(); $migrator = new Migrator($repository, $resolver, $filesystem); return $migrator; }; $di['db'] = function () use($params, $di) { class_alias(DB::class, 'DB'); DB::setContainer($di); $capsule = new Capsule(); $capsule->setEventDispatcher(new Dispatcher(new Container())); $capsule->setAsGlobal(); $capsule->bootEloquent(); $capsule->addConnection($params); if (class_exists(MongoDbConnection::class)) { $capsule->getDatabaseManager()->extend('mongodb', function ($config) { return new MongoDbConnection($config); }); } return $capsule; }; $di['dbManager'] = function () use($params, $di) { $dbCapsule = $di['db']; return $dbCapsule->getDatabaseManager(); }; $di['db']; }
/** * Register Illuminate with the application * * @param array $config * @param Application $app * @return void */ public function register(Application $app) { // Set some sane defaults $defaults = array('boot' => true, 'eloquent' => true, 'fetch' => PDO::FETCH_CLASS, 'global' => true, 'default' => 'default', 'connections' => array('default' => array('driver' => 'mysql', 'host' => 'localhost', 'database' => 'silex', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => null))); // Merge in any passed configuration $this->config = array_merge($defaults, $app['db.config']); // Make sure all connections have all required fields if (isset($this->config['connections'])) { foreach ($this->config['connections'] as $index => $connection) { $this->config['connections'][$index] = array_merge($defaults['connections']['default'], $connection); } } // Create a container for the database pool $app['db.container'] = $app->share(function () { return new Container(); }); // Create the connections to the datbase $app['db'] = $app->share(function () use($app) { $db = new Capsule($app['db.container']); // Set PDO fetch mode as per configuration $db->setFetchMode($this->config['fetch']); // Set as global, use eloquent as per configuration if ($this->config['eloquent']) { $db->bootEloquent(); } if ($this->config['global']) { $db->setAsGlobal(); } // Set up the event dispatcher if we have it available if (class_exists('Illuminate\\Events\\Dispatcher')) { $db->setEventDispatcher(new Dispatcher($app['db.container'])); } // Initialise each connection foreach ($this->config['connections'] as $connection => $options) { $db->addConnection(array_replace($this->config['connections'][$this->config['default']], $options), $connection); // If we're in debug mode we're going to want to use the query log, otherwise leave it disabled // to speed up queries and reduce memory usage if ($app['debug']) { $db->getConnection($connection)->enableQueryLog(); } } // Finally set default connection $db->getDatabaseManager()->setDefaultConnection($this->config['default']); return $db; }); }
/** * Create a new Validator factory instance. * * @param \Illuminate\Database\Capsule\Manager $db * @return \Illuminate\Validation\Factory */ public function __construct($db) { if (!$this->factory) { /** * illuminate/translation (Translator) package need for correct work of Validator */ $translator = new Translator('en'); $this->factory = new Factory($translator); /** * To set database presence verifier we need database connection instance, * which is implements ConnectionResolverInterface. For this purpose * Illuminate\Database\Capsule\Manager class, which we get from $db arg, * have getDatabaseManager() function. * With defined DatabasePresenceVerifier we can use rules such as: * unique:table,column,except,idColumn * exists:table,column */ $dbManager = $db->getDatabaseManager(); $this->factory->setPresenceVerifier(new DatabasePresenceVerifier($dbManager)); } return $this->factory; }
public function register(Container $pimple) { $pimple['db'] = function ($pimple) { $db = new Manager(); $db->addConnection(['driver' => 'mysql', 'host' => $pimple['config']['db.host'], 'database' => $pimple['config']['db.database'], 'username' => $pimple['config']['db.username'], 'password' => $pimple['config']['db.password'], 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => $pimple['config']['db.prefix']]); $db->setEventDispatcher($pimple['events']); // Make this Capsule instance available globally via static methods... (optional) $db->setAsGlobal(); // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher()) $db->bootEloquent(); if ($pimple['config']['log.sql']) { // 记录查询过的日志 $manager = $db->getDatabaseManager(); try { $manager->listen(function ($query, $bindings = null, $time = null, $connectionName = null) use($manager, $pimple) { // Laravel 5.2 changed the way some core events worked. We must account for // the first argument being an "event object", where arguments are passed // via object properties, instead of individual arguments. if ($query instanceof \Illuminate\Database\Events\QueryExecuted) { $bindings = $query->bindings; $time = $query->time; $connection = $query->connection; $query = $query->sql; } else { $connection = $manager->connection($connectionName); } $pimple['log']->debug($query, $bindings); $pimple['sql_log']->set($query, $bindings); }); } catch (\Exception $e) { $pimple['log']->debug($e->getMessage()); } } return $db; }; }
/** * Initialise a new collector * * @param Capsule $database * @return void */ public function __construct(Capsule $database) { $this->connections = $database->getDatabaseManager()->getConnections(); }
$validator = $validation->make($data, $rules); if ($validator->fails()) { $errors = $validator->errors(); } return $app->render('form.php', ['posted' => true, 'errors' => $errors, 'email' => $_POST['email']]); }); // For a thorough example, we establish a database connection // to drive the database presence verifier used by the validator. // If you do not need to validate against values in the database, // the database presence verifier and related code can be removed. $app->get('/database', function () use($app) { return $app->render('form.php', ['posted' => false, 'errors' => null, 'email' => '']); }); $app->post('/database', function () use($app) { $capsule = new Capsule(); $capsule->addConnection(['driver' => 'mysql', 'host' => 'localhost', 'database' => 'illuminate_non_laravel', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '']); $loader = new FileLoader(new Filesystem(), 'lang'); $translator = new Translator($loader, 'en'); $presence = new DatabasePresenceVerifier($capsule->getDatabaseManager()); $validation = new Factory($translator, new Container()); $validation->setPresenceVerifier($presence); $data = ['email' => $_POST['email']]; $rules = ['email' => 'required|email|unique:users']; $errors = null; $validator = $validation->make($data, $rules); if ($validator->fails()) { $errors = $validator->errors(); } return $app->render('form.php', ['posted' => true, 'errors' => $errors, 'email' => $_POST['email']]); }); $app->run();
private function initDb() { $capsule = new Capsule(); $capsule->addConnection(['driver' => 'sqlite', 'host' => 'localhost', 'database' => ':memory:', 'prefix' => '']); $capsule->setEventDispatcher(new Dispatcher(new Container())); $capsule->setAsGlobal(); $capsule->bootEloquent(); Capsule::schema()->create('settings', function ($table) { $table->increments('id'); $table->string('key')->index()->unique(); $table->string('value')->longText(); }); return $capsule->getDatabaseManager(); }
ini_set('error_reporting', E_ALL); require_once __DIR__ . '/vendor/autoload.php'; use Illuminate\Container\Container; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Facade; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Events\Dispatcher; use Psr\Log\LoggerInterface; use Monolog\Logger; use Monolog\Handler\ErrorLogHandler; use Jvelo\Datatext\Cli\Cli; $capsule = new DB(); $capsule->addConnection(['driver' => 'pgsql', 'host' => 'localhost', 'database' => 'datatext', 'username' => 'jerome', 'password' => '', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public']); $container = new Container(); $container->singleton("db", function () use($capsule) { return $capsule->getDatabaseManager(); }); $container->singleton("datatext.user_provider", '\\Jvelo\\Datatext\\ConstantAdminUserProvider'); $container->singleton("datatext.shortcodes", '\\Jvelo\\Datatext\\Shortcodes\\Shortcodes'); $container->singleton("datatext.assets_manager", '\\Jvelo\\Datatext\\Assets\\DefaultAssets'); $container->singleton("datatext.api.pages", '\\Jvelo\\Datatext\\Api\\Pages'); Facade::setFacadeApplication($container); $capsule->setEventDispatcher(new Dispatcher($container)); $capsule->setAsGlobal(); $capsule->bootEloquent(); $container->bind('CreatePageAndObjectTables', '\\CreatePageAndObjectTables'); $container->bind('Schema', '\\Illuminate\\Database\\Schema\\Builder'); $container->singleton('app', function () use($container) { return $container; }); $cli = new Cli();
}); $app->singleton('cache', function () use($app) { return new CacheManager($app); }); $app->singleton('db', function () use($app) { $config = $app['config']; $default = $config['database.default']; $fetch = $config['database.fetch']; $db = new Capsule($app); $config['database.fetch'] = $fetch; $config['database.default'] = $default; $db->addConnection($config['database.connections'][$default]); $db->setEventDispatcher($app['events']); $db->setAsGlobal(); $db->bootEloquent(); return $db->getDatabaseManager(); }); /* |-------------------------------------------------------------------------- | Register The Aliased Auto Loader |-------------------------------------------------------------------------- | | We register an auto-loader "before" the Composer loader that can load | aliased classes with out their namespaces. We'll add it to the stack here. | */ spl_autoload_register(function ($className) use($app) { if (isset($app['config']['app.aliases'][$className])) { $app['db']; //lazy initialization of DB return class_alias($app['config']['app.aliases'][$className], $className);
<?php use Symfony\Component\Console\Output\NullOutput; use Phinx\Config\Config; use Phinx\Migration\Manager as MigrationManager; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Connection; $loader = (require __DIR__ . '/../vendor/autoload.php'); // auto-load custom PHPUnit constraints $loader->add('', __DIR__ . '/constraints/'); /** * Create and seed an in-memory sqlite database for testing * Using Phinx for migrations/seeding */ $config = new Config(['paths' => ['migrations' => __DIR__ . '/migrations'], 'environments' => ['default_migration_table' => 'phinxlog', 'default_database' => 'test', 'test' => ['name' => ':memory:', 'adapter' => 'sqlite', 'memory' => true]]]); $migrationManager = new MigrationManager($config, new NullOutput()); // get the PDO object used by Phinx $pdo = $migrationManager->getEnvironment('test')->getAdapter()->getConnection(); /** * Make Eloquent use the PDO object provided by Phinx */ $capsule = new Capsule(); $capsule->addConnection([], 'default'); $capsule->getDatabaseManager()->extend('default', function () use($pdo) { return new Connection($pdo); }); $capsule->bootEloquent(); // run migrations $migrationManager->migrate('test');
/** * Configures Ardent to be used outside of Laravel - correctly setting Eloquent and Validation modules. * @todo Should allow for additional language files. Would probably receive a Translator instance as an optional argument, or a list of translation files. * * @param array $connection Connection info used by {@link \Illuminate\Database\Capsule\Manager::addConnection}. * Should contain driver, host, port, database, username, password, charset and collation. */ public static function configureAsExternal(array $connection) { $db = new DatabaseCapsule(); $db->addConnection($connection); $db->setEventDispatcher(new Dispatcher(new Container())); //TODO: configure a cache manager (as an option) // Make this Capsule instance available globally via static methods $db->setAsGlobal(); $db->bootEloquent(); $translator = new Translator('en'); $translator->addLoader('file_loader', new PhpFileLoader()); $translator->addResource('file_loader', dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'en' . DIRECTORY_SEPARATOR . 'validation.php', 'en'); self::$externalValidator = true; self::$validationFactory = new ValidationFactory($translator); self::$validationFactory->setPresenceVerifier(new DatabasePresenceVerifier($db->getDatabaseManager())); }
/** @test */ public function it_should_support_the_database_session_handler() { $database = __DIR__ . '/session.sqlite'; if (file_exists($database)) { unlink($database); } touch($database); $connection = ['driver' => 'sqlite', 'database' => $database, 'prefix' => '']; $table = 'sessions'; $Session = new Session(['driver' => 'database', 'connection' => $connection, 'table' => $table]); $Session->start(); $this->assertions($Session); $sid = $Session->getId(); register_shutdown_function(function () use($sid, $connection, $table) { $Database = new Manager(); $Database->addConnection($connection); $Db = $Database->getDatabaseManager(); $results = $Db->select('select id from ' . $table . ' LIMIT 1'); $this->assertEquals(1, count($results)); $row = array_shift($results); $this->assertEquals($sid, $row['id']); unlink($connection['database']); }); }
<?php use Illuminate\Database\Capsule\Manager as Capsule; require __DIR__ . '/../comments/start.php'; // Connection to the old database. $capsule = new Capsule(); $capsule->addConnection(require __DIR__ . '/database.php'); $capsule->setFetchMode(PDO::FETCH_OBJ); $db = $capsule->getDatabaseManager(); // Get the comment root id for the given parent id. function get_root_id($id) { global $db; $comment = $db->table('comments')->where('id', $id)->first(['id', 'parent']); if (!$comment) { return $id; } if (!empty($comment->parent)) { return get_root_id($comment->parent); } return $comment->id; } // Select all comments from old table. $comments = $db->table('comments')->get(); $status = ['pending', 'approved', 'spam']; Comment::unguard(); // Insert the old comments into the new table. foreach ($comments as $comment) { if (empty($comment->parent)) { $rootId = null; } else {