本文整理汇总了PHP中Doctrine\DBAL\DriverManager::getConnection方法的典型用法代码示例。如果您正苦于以下问题:PHP DriverManager::getConnection方法的具体用法?PHP DriverManager::getConnection怎么用?PHP DriverManager::getConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Doctrine\DBAL\DriverManager
的用法示例。
在下文中一共展示了DriverManager::getConnection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getSpecifiedConnectionParams
private static function getSpecifiedConnectionParams()
{
$realDbParams = self::getParamsForMainConnection();
if (!self::$initialized) {
$tmpDbParams = self::getParamsForTemporaryConnection();
$realConn = DriverManager::getConnection($realDbParams);
// Connect to tmpdb in order to drop and create the real test db.
$tmpConn = DriverManager::getConnection($tmpDbParams);
$platform = $tmpConn->getDatabasePlatform();
if ($platform->supportsCreateDropDatabase()) {
$dbname = $realConn->getDatabase();
$realConn->close();
$tmpConn->getSchemaManager()->dropAndCreateDatabase($dbname);
$tmpConn->close();
} else {
$sm = $realConn->getSchemaManager();
$schema = $sm->createSchema();
$stmts = $schema->toDropSql($realConn->getDatabasePlatform());
foreach ($stmts as $stmt) {
$realConn->exec($stmt);
}
}
self::$initialized = true;
}
return $realDbParams;
}
示例2: getEntityManagerInstanceMock
/**
* Just for internal use, could be overridden in child classes
* User $em property in case if you need EntityManager
*
* @return EntityManagerMock
*/
protected function getEntityManagerInstanceMock()
{
$this->config = Setup::createAnnotationMetadataConfiguration(array('./Fixtures'), true);
$this->config->setQuoteStrategy(new QuotingStrategy());
$conn = array('driverClass' => 'Luxifer\\Tests\\Mocks\\DriverMock', 'wrapperClass' => 'Luxifer\\Tests\\Mocks\\ConnectionMock', 'user' => 'john', 'password' => 'wayne');
$conn = DriverManager::getConnection($conn, $this->config);
$this->config->setProxyDir(__DIR__ . '/Proxies');
$this->config->setProxyNamespace('Luxifer\\Tests\\Proxies');
$this->config->addCustomDatetimeFunction('date', 'Luxifer\\DQL\\Datetime\\Date');
$this->config->addCustomDatetimeFunction('datediff', 'Luxifer\\DQL\\Datetime\\DateDiff');
$this->config->addCustomDatetimeFunction('day', 'Luxifer\\DQL\\Datetime\\Day');
$this->config->addCustomDatetimeFunction('dayofmonth', 'Luxifer\\DQL\\Datetime\\DayOfMonth');
$this->config->addCustomDatetimeFunction('week', 'Luxifer\\DQL\\Datetime\\Week');
$this->config->addCustomDatetimeFunction('dayofweek', 'Luxifer\\DQL\\Datetime\\DayOfWeek');
$this->config->addCustomDatetimeFunction('dayofyear', 'Luxifer\\DQL\\Datetime\\DayOfYear');
$this->config->addCustomDatetimeFunction('hour', 'Luxifer\\DQL\\Datetime\\Hour');
$this->config->addCustomDatetimeFunction('minute', 'Luxifer\\DQL\\Datetime\\Minute');
$this->config->addCustomDatetimeFunction('month', 'Luxifer\\DQL\\Datetime\\Month');
$this->config->addCustomDatetimeFunction('quarter', 'Luxifer\\DQL\\Datetime\\Quarter');
$this->config->addCustomDatetimeFunction('second', 'Luxifer\\DQL\\Datetime\\Second');
$this->config->addCustomDatetimeFunction('time', 'Luxifer\\DQL\\Datetime\\Time');
$this->config->addCustomDatetimeFunction('year', 'Luxifer\\DQL\\Datetime\\Year');
$this->config->addCustomDatetimeFunction('convert_tz', 'Luxifer\\DQL\\Datetime\\ConvertTZ');
$this->config->addCustomDatetimeFunction('date_format', 'Luxifer\\DQL\\Datetime\\DateFormat');
$this->config->addCustomDatetimeFunction('concat_ws', 'Luxifer\\DQL\\String\\ConcatWs');
return EntityManagerMock::create($conn, $this->config);
}
示例3: connectDatabase
private function connectDatabase(OutputInterface $output)
{
$param = array();
$param['host'] = $this->dialog->ask($output, '<question>Where is your database server? [localhost]</question> ', 'localhost');
$param['user'] = $this->dialog->ask($output, '<question>What is your database username? [root]</question> ', 'root');
$param['password'] = $this->dialog->ask($output, '<question>What is your database password?</question> ', '');
$param['driver'] = 'pdo_mysql';
// Save dbName for later use to create database
$this->dbName = $this->dialog->ask($output, '<question>What is your database name? [BungaWire]</question> ', 'BungaWire');
$output->writeln('');
// Write empty line for easy read
$config = new Configuration();
$this->dbConnection = DriverManager::getConnection($param, $config);
$this->dbConnection->connect();
if ($this->dbConnection->isConnected() === false) {
$output->writeln('Database connection failed, please check your setting');
$output->writeln('You connection configuration is:');
$output->writeln('host: ' . $param['host']);
$output->writeln('user: ' . $param['user']);
$output->writeln('password: ' . $param['password']);
$output->writeln('Database Name: ' . $param['dbname']);
$output->writeln('Driver: ' . $param['driver']);
$output->writeln($this->dbConnection->errorInfo());
$output->writeln('Please try again!');
$this->connectDatabase($output);
} else {
$output->writeln('Database connected!');
}
}
示例4: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$database = array();
if (extension_loaded('pdo_pgsql')) {
$database['pdo_pgsql'] = 'PostgreSQL';
}
if (extension_loaded('pdo_mysql')) {
$database['pdo_mysql'] = 'MySQL';
}
if (extension_loaded('pdo_sqlite')) {
$database['pdo_sqlite'] = 'SQLite(開発者用)';
}
$builder->add('database', 'choice', array('label' => 'データベースの種類', 'choices' => $database, 'expanded' => false, 'multiple' => false, 'constraints' => array(new Assert\NotBlank())))->add('database_host', 'text', array('label' => 'データベースのホスト名', 'required' => false))->add('database_port', 'text', array('label' => 'ポート番号', 'required' => false))->add('database_name', 'text', array('label' => 'データベース名', 'constraints' => array(new Assert\Callback(array($this, 'validate')))))->add('database_user', 'text', array('label' => 'ユーザ名', 'constraints' => array(new Assert\Callback(array($this, 'validate')))))->add('database_password', 'password', array('label' => 'パスワード', 'required' => false))->addEventListener(FormEvents::POST_SUBMIT, function ($event) {
$form = $event->getForm();
$data = $form->getData();
try {
$config = new \Doctrine\DBAL\Configuration();
if ($data['database'] == 'pdo_sqlite') {
$connectionParams = array('driver' => $data['database'], 'path' => __DIR__ . '/../../../../../app/config/eccube/eccube.db');
} else {
$connectionParams = array('dbname' => $data['database_name'], 'user' => $data['database_user'], 'password' => $data['database_password'], 'host' => $data['database_host'], 'driver' => $data['database'], 'port' => $data['database_port']);
}
// todo MySQL, PostgreSQLのバージョンチェックも欲しい.DBALで接続すればエラーになる?
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
$conn->connect();
} catch (\Exception $e) {
$form['database']->addError(new FormError('データベースに接続できませんでした。' . $e->getMessage()));
}
});
}
示例5: createDatabase
protected static function createDatabase()
{
if (empty(getenv('PGSQL_HOST')) && file_exists(__DIR__ . '/../../.env')) {
$dotenv = new Dotenv(__DIR__ . '/../../');
$dotenv->load();
}
if (empty(getenv('PGSQL_HOST')) || empty(getenv('PGSQL_USER'))) {
throw new \RuntimeException('Create a .env file with PGSQL_HOST, PGSQL_USER, and PGSQL_PASS to run this test.');
}
$pass = getenv('PGSQL_PASS') ? getenv('PGSQL_PASS') : '';
$pdo = new \PDO('pgsql:host=' . getenv('PGSQL_HOST'), getenv('PGSQL_USER'), $pass);
$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
self::$connection = DriverManager::getConnection(['driver' => 'pdo_pgsql', 'pdo' => $pdo, 'dbname' => 'public']);
self::$connection->query('drop schema public cascade');
self::$connection->query('create schema public');
self::$connection->query('CREATE TABLE extended_data_objects (
id SERIAL PRIMARY KEY,
"isDeleted" BOOLEAN NOT NULL DEFAULT FALSE,
"myColumn" VARCHAR(255) NOT NULL,
"myNullableColumn" INT NULL DEFAULT NULL,
"otherDataObjectId" INT NULL
)');
self::$connection->query('CREATE TABLE other_data_objects (
id SERIAL PRIMARY KEY,
"isDeleted" BOOLEAN NOT NULL DEFAULT FALSE,
"name" VARCHAR(255) NOT NULL,
"extendedDataObjectId" INT NULL REFERENCES extended_data_objects (id)
)');
self::$connection->query('CREATE TABLE extended_other_rel (
"extendedDataObjectId" INT NOT NULL REFERENCES extended_data_objects (id),
"otherDataObjectId" INT NOT NULL REFERENCES other_data_objects (id)
)');
}
示例6: setUp
protected function setUp()
{
parent::setUp();
$this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::SQLITE_PATH], new Configuration());
$config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../..'], true);
$this->entityManager = EntityManager::create($this->connection, $config);
}
示例7: instance
/**
* 单例模式,获取一个指定的实例
*
* // 加载默认实例
* $db = Database::instance();
*
* // 指定实例名称和配置
* $db = Database::instance('custom', $config);
*
* @param string $name 实例名
* @param array $config 配置参数
* @return Connection
*/
public static function instance($name = null, array $config = null)
{
if (null === $name) {
$name = Db::$default;
}
if (!isset(Db::$instances[$name])) {
// 读取配置
if (null === $config) {
$config = (array) Config::load(self::$configFile)->get($name);
Base::getLog()->debug(__METHOD__ . ' get default config', ['name' => $name]);
}
// 合并默认配置
if (isset(self::$defaultConfig[Arr::get($config, 'driver')])) {
$config = Arr::merge(self::$defaultConfig[Arr::get($config, 'driver')], $config);
Base::getLog()->debug(__METHOD__ . ' merge config', ['name' => $name]);
}
$conn = DriverManager::getConnection($config);
Base::getLog()->debug(__METHOD__ . ' create dbal connection', ['name' => $name]);
// 额外注册字段类型
if (isset(self::$mappingType[Arr::get($config, 'driver')])) {
$platform = $conn->getDatabasePlatform();
foreach (self::$mappingType[Arr::get($config, 'driver')] as $dbType => $doctrineType) {
if (!$platform->hasDoctrineTypeMappingFor($dbType)) {
Base::getLog()->debug(__METHOD__ . ' add dbal mapping type', ['raw' => $dbType, 'dbal' => $doctrineType]);
$platform->registerDoctrineTypeMapping($dbType, $doctrineType);
}
}
}
Db::$instances[$name] = $conn;
Base::getLog()->debug(__METHOD__ . ' save db instance', ['name' => $name]);
}
return Db::$instances[$name];
}
示例8: addConnection
/**
* Add database connection
*
* @param string $name Unique name for the connection
* @param string $dsn DSN string for this connection
* @param boolean $defaut Use this connection as the default? The first connection added is automatically set as the default, even if this flag is false.
*
* @return \Doctrine\DBAL\Connection
* @throws \Spot\Exception
*/
public function addConnection($name, $dsn, $default = false)
{
// Connection name must be unique
if (isset($this->_connections[$name])) {
throw new Exception("Connection for '" . $name . "' already exists. Connection name must be unique.");
}
if ($dsn instanceof DBAL\Connection) {
$connection = $dsn;
} else {
if (is_array($dsn)) {
$connectionParams = $dsn;
} else {
$connectionParams = $this->parseDsn($dsn);
if ($connectionParams === false) {
throw new Exception("Unable to parse given DSN string");
}
}
$config = new DBAL\Configuration();
$connection = DBAL\DriverManager::getConnection($connectionParams, $config);
}
// Set as default connection?
if (true === $default || null === $this->_defaultConnection) {
$this->_defaultConnection = $name;
}
// Store connection and return adapter instance
$this->_connections[$name] = $connection;
return $connection;
}
示例9: setUp
protected function setUp()
{
$this->app = $app = new Container();
$db_config = ['driver' => 'pdo_sqlite', 'dbname' => 'sqlite:///:memory:'];
$models = ['post.model' => function () use($app) {
return new Post($app);
}, 'comment.model' => 'Comment'];
$app['db'] = function () use($db_config) {
$db = \Doctrine\DBAL\DriverManager::getConnection($db_config);
$sql = file_get_contents(codecept_data_dir() . '/dump.sql');
$db->exec($sql);
return $db;
};
foreach ($models as $name => $class) {
if (is_callable($class)) {
$callable = $class;
} else {
$callable = function () use($class, $app) {
return new $class($app);
};
}
$app[$name] = $app->factory($callable);
}
$this->loadFixtures();
}
示例10: execute
/**
* {@inheritDoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$connection = $this->getDoctrineConnection($input->getOption('connection'));
$params = $connection->getParams();
if (isset($params['master'])) {
$params = $params['master'];
}
$name = isset($params['path']) ? $params['path'] : (isset($params['dbname']) ? $params['dbname'] : false);
if (!$name) {
throw new \InvalidArgumentException("Connection does not contain a 'path' or 'dbname' parameter and cannot be dropped.");
}
unset($params['dbname']);
$tmpConnection = DriverManager::getConnection($params);
// Only quote if we don't have a path
if (!isset($params['path'])) {
$name = $tmpConnection->getDatabasePlatform()->quoteSingleIdentifier($name);
}
$error = false;
try {
$tmpConnection->getSchemaManager()->createDatabase($name);
$output->writeln(sprintf('<info>Created database for connection named <comment>%s</comment></info>', $name));
} catch (\Exception $e) {
$output->writeln(sprintf('<error>Could not create database for connection named <comment>%s</comment></error>', $name));
$output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
$error = true;
}
$tmpConnection->close();
return $error ? 1 : 0;
}
示例11: getDBAL
public function getDBAL($conn = 'default')
{
if (in_array($conn, self::$dbal_conns)) {
return self::$dbal_conns[$conn];
}
return self::$dbal_conns[$conn] = \Doctrine\DBAL\DriverManager::getConnection($this->getConnection($conn), new \Doctrine\DBAL\Configuration());
}
示例12: initDb
public function initDb()
{
$params = $this->connection->getParams();
$name = $params['dbname'];
unset($params['dbname']);
$conn = DriverManager::getConnection($params);
$conn->exec('CREATE DATABASE IF NOT EXISTS ' . $name);
$conn->exec('USE ' . $name);
$conn->exec('CREATE TABLE IF NOT EXISTS bl_run (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(64),
project_name VARCHAR(64) NOT NULL,
properties TEXT NOT NULL,
created_at DATETIME NOT NULL
)');
$conn->exec('CREATE TABLE IF NOT EXISTS bl_run_unit (
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
run_id INTEGER NOT NULL,
feature TEXT NOT NULL,
created_at DATETIME NOT NULL,
started_at DATETIME,
finished_at DATETIME,
return_code INTEGER,
output_files TEXT
)');
}
示例13: getDbal
/**
* @return \Doctrine\DBAL\Connection
*/
protected function getDbal()
{
if (self::$dbal === null) {
self::$dbal = DriverManager::getConnection(array('pdo' => $this->getPdo()));
}
return self::$dbal;
}
示例14: setUp
/**
* Initializes the database (once).
*
* @throws \Doctrine\DBAL\DBALException
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\Tools\ToolsException
*/
protected function setUp()
{
if (null === static::$_conn) {
$dbPath = __DIR__ . '/../../../db.sqlite';
if (file_exists($dbPath)) {
unlink($dbPath);
}
$params = ['driver' => 'pdo_sqlite', 'path' => $dbPath];
static::$_conn = DriverManager::getConnection($params);
static::$_conn->getConfiguration()->setSQLLogger(null);
}
if (null === static::$_em) {
$paths = [__DIR__ . '/../../../../../src/Ekyna/Commerce/Bridge/Doctrine/ORM/Resources/mapping'];
$isDevMode = true;
$config = Setup::createXMLMetadataConfiguration($paths, $isDevMode);
$em = EntityManager::create(static::$_conn, $config);
$classes = [];
foreach (static::$_classes as $class) {
array_push($classes, $em->getClassMetadata($class));
}
$schemaTool = new SchemaTool($em);
$schemaTool->dropSchema($classes);
$schemaTool->createSchema($classes);
// Load fixtures
$loader = new Loader();
$loader->loadFromDirectory(__DIR__ . '/../../../../../src/Ekyna/Commerce/Bridge/Doctrine/Fixtures');
$purger = new ORMPurger();
$executor = new ORMExecutor($em, $purger);
$executor->execute($loader->getFixtures());
static::$_em = $em;
}
}
示例15: newConnection
/**
* Get an instance of a DBAL Connection
*
* @param sting $name the connection name
* @return Doctrine\DBAL\Connection
*/
public function newConnection()
{
$configuration = new DBAL\Configuration();
$logger = new MSQLLogger($this);
$configuration->setSQLLogger($logger);
return DBAL\DriverManager::getConnection($this->config, $configuration);
}