本文整理汇总了PHP中Cake\Datasource\ConnectionManager::get方法的典型用法代码示例。如果您正苦于以下问题:PHP ConnectionManager::get方法的具体用法?PHP ConnectionManager::get怎么用?PHP ConnectionManager::get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cake\Datasource\ConnectionManager
的用法示例。
在下文中一共展示了ConnectionManager::get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: setUp
/**
* setup
*
* @return void
*/
public function setUp()
{
parent::setUp();
$this->connection = ConnectionManager::get('test');
$this->user = TableRegistry::get('Users', ['table' => 'counter_cache_users', 'connection' => $this->connection]);
$this->post = new PostTable(['alias' => 'Post', 'table' => 'counter_cache_posts', 'connection' => $this->connection]);
}
示例2: get
/**
* Get/Create an instance from the registry.
*
* When getting an instance, if it does not already exist,
* a new instance will be created using the provide alias, and options.
*
* @param string $alias The name of the alias to get.
* @param array $options Configuration options for the type constructor.
* @return \Cake\ElasticSearch\Type
*/
public static function get($alias, array $options = [])
{
if (isset(static::$instances[$alias])) {
if (!empty($options) && static::$options[$alias] !== $options) {
throw new RuntimeException(sprintf('You cannot configure "%s", it already exists in the registry.', $alias));
}
return static::$instances[$alias];
}
static::$options[$alias] = $options;
list(, $classAlias) = pluginSplit($alias);
$options = $options + ['name' => Inflector::underscore($classAlias)];
if (empty($options['className'])) {
$options['className'] = Inflector::camelize($alias);
}
$className = App::className($options['className'], 'Model/Type', 'Type');
if ($className) {
$options['className'] = $className;
} else {
if (!isset($options['name']) && strpos($options['className'], '\\') === false) {
list(, $name) = pluginSplit($options['className']);
$options['name'] = Inflector::underscore($name);
}
$options['className'] = 'Cake\\ElasticSearch\\Type';
}
if (empty($options['connection'])) {
$connectionName = $options['className']::defaultConnectionName();
$options['connection'] = ConnectionManager::get($connectionName);
}
static::$instances[$alias] = new $options['className']($options);
return static::$instances[$alias];
}
示例3: execute
/**
* Dumps the current schema to be used when baking a diff
*
* @param \Symfony\Component\Console\Input\InputInterface $input the input object
* @param \Symfony\Component\Console\Output\OutputInterface $output the output object
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->setInput($input);
$this->bootstrap($input, $output);
$this->output($output);
$path = $this->getOperationsPath($input);
$connectionName = $input->getOption('connection') ?: 'default';
$connection = ConnectionManager::get($connectionName);
$collection = $connection->schemaCollection();
$options = ['require-table' => true, 'plugin' => $this->getPlugin($input)];
$tables = $this->getTablesToBake($collection, $options);
$dump = [];
if (empty($tables)) {
$this->output()->writeln('<info>No tables were found : the dump file was not created</info>');
return;
}
foreach ($tables as $table) {
$schema = $collection->describe($table);
$dump[$table] = $schema;
}
$filePath = $path . DS . 'schema-dump-' . $connectionName . '.lock';
$output->writeln(sprintf('<info>Writing dump file `%s`...</info>', $filePath));
if (file_put_contents($filePath, serialize($dump))) {
$output->writeln(sprintf('<info>Dump file `%s` was successfully written</info>', $filePath));
} else {
$output->writeln(sprintf('<error>An error occurred while writing dump file `%s`</error>', $filePath));
}
}
示例4: add
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
if ($this->Crisis->find('all')->count() === 0) {
ConnectionManager::get('default')->execute('ALTER TABLE crisis AUTO_INCREMENT 1');
}
$crisi = $this->Crisis->newEntity();
if (isset($this->request->data)) {
$crisi = $this->Crisis->patchEntity($crisi, $this->request->data);
//do magic here
$crisis = $this->Crisis->find('all');
$delta_search = 0.5;
foreach ($crisis as $crisi_db) {
if (abs($crisi_db['latitude'] - $crisi['latitude']) < $delta_search && abs($crisi_db['latitude'] - $crisi['latitude']) < $delta_search && $crisi_db->state != 'over') {
//1° lat/long-> 111 km
$crisi_db->severity += 1;
if ($this->Crisis->save($crisi_db)) {
$this->Flash->success('Cette crise a déjà été signalée, nous incrémentons sa gravité.');
} else {
$this->Flash->error('La crise n\'a pas pu être enregistrée.');
}
return $this->redirect(['controller' => 'Homes', 'action' => 'index']);
}
}
if ($this->Crisis->save($crisi)) {
$this->Flash->success(__('La crise a bien été enregistrée.'));
} else {
$this->Flash->error(__('La crise n\'a pas pu être enregistrée.'));
}
return $this->redirect(['controller' => 'Homes', 'action' => 'index']);
}
}
示例5: init
public function init()
{
parent::init();
// 1. Not all fixtures want to use the dev db.
if (is_null($this->tableName)) {
return;
}
// 2. We need to do this to ensure that the tables really do use the connection to the
// dev db.
TableRegistry::remove($this->tableName);
$table = TableRegistry::get($this->tableName, ['connection' => ConnectionManager::get('dev')]);
//if(!is_null($this->joinTableName)) {
//TableRegistry::remove($this->joinTableName);
//$n=TableRegistry::get($this->joinTableName, ['connection' => ConnectionManager::get('fixture')]);
//}
// 3. Now build the query to retrieve the source records
$query = new Query(ConnectionManager::get('dev'), $table);
$query->find('all');
//if(!is_null($this->order)) $query->order($this->order);
//if(!is_null($this->joinTableName)) $query->leftJoin($this->joinTableName,'semesters.id = sections.semester_id');
//$c=$query->count();
// 4. Copy the records
/* @var \Cake\ORM\Entity $record */
foreach ($query as $record) {
$this->records[] = $record->toArray();
}
// 5. Do this again to ensure that the table uses the 'test' connection.
TableRegistry::remove($this->tableName);
TableRegistry::get($this->tableName, ['connection' => ConnectionManager::get('test')]);
//if(!is_null($this->joinTableName)) {
//TableRegistry::remove($this->joinTableName);
//TableRegistry::get($this->joinTableName, ['connection' => ConnectionManager::get('test')]);
//}
}
示例6: index
public function index()
{
$conn = ConnectionManager::get('default');
//Create gallery
$query = 'CREATE TABLE gallery (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
category_id INT(11),
title VARCHAR(50),
description TEXT,
img VARCHAR(50),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
)';
$conn->query($query);
//Create gallery categories
$query = 'CREATE TABLE category (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
description TEXT,
img VARCHAR(50),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
)';
$conn->query($query);
$this->Flash->success('Successfully installed.');
return $this->redirect(['controller' => 'category', 'action' => 'index']);
}
示例7: add
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add($crisis_id = null)
{
if ($this->Infos->find('all')->count() === 0) {
ConnectionManager::get('default')->execute('ALTER TABLE infos AUTO_INCREMENT 1');
}
if ($crisis_id != null) {
$user_id = $this->Auth->user()['id'];
$info = $this->Infos->newEntity();
if ($this->request->is('post')) {
$info->crisis_id = $crisis_id;
$info->user_id = $user_id;
$info = $this->Infos->patchEntity($info, $this->request->data);
if ($this->Infos->save($info)) {
$this->Flash->success(__('L\'information a bien été enregistrée.'));
return $this->redirect(['controller' => 'crisis', 'action' => 'view', $crisis_id]);
} else {
$this->Flash->error(__('L\'information n\'a pas pu être enregistrée.'));
}
}
$Crisis = $this->Infos->Crisis->find('list', ['limit' => 200]);
$users = $this->Infos->Users->find('list', ['limit' => 200]);
$this->set(compact('info', 'Crisis', 'users', 'crisis_id'));
$this->set('_serialize', ['info']);
} else {
$this->Flash->error(__('Vous devez spécifier la crise liée à cette information.'));
return $this->redirect(['controller' => 'Homes', 'action' => 'index']);
}
}
示例8: add
public function add()
{
$palestrante = $this->Palestrantes->newEntity();
if ($this->request->is('post')) {
if (is_uploaded_file($this->request->data['foto']['tmp_name'])) {
$filename = $this->request->data['foto']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
while (true) {
$filename = uniqid(rand(), true) . '.' . $ext;
if (!'imagestore/' . $filename) {
break;
}
}
move_uploaded_file($this->request->data['foto']['tmp_name'], 'imagestore/' . $filename);
// store the filename in the array to be saved to the db
$this->request->data['foto'] = $filename;
}
$palestrante = $this->Palestrantes->patchEntity($palestrante, $this->request->data);
if ($this->Palestrantes->save($palestrante)) {
$this->Flash->default(__('Palestrante adicionado com sucesso'));
return $this->redirect(['action' => 'view', $palestrante->id]);
}
$this->Flash->error(__('Incrição não realizada, verifique se preencheu o formulário corretamente!'));
}
$connection = ConnectionManager::get('default');
$result = $connection->execute('SELECT id, nome FROM users')->fetchAll('assoc');
$usersList = array();
$usersList[null] = 'Selecione';
foreach ($result as $row) {
$usersList[$row['id']] = $row['nome'];
}
$this->set('usersList', $usersList);
$this->set('palestrante', $palestrante);
}
示例9: insert
public function insert(UploadDTO\CustomerFeedbackUploadDto $customerFeedback, $userInfo)
{
$conn = ConnectionManager::get('default');
$conn->begin();
$tableObj = $this->connect();
$customerFeedbackCounter = 0;
try {
foreach ($customerFeedback->feedback as $feedback) {
$newCustomerFeedback = $tableObj->newEntity();
$newCustomerFeedback->CustId = $customerFeedback->custId;
$newCustomerFeedback->UserId = $userInfo->userId;
$newCustomerFeedback->FeedbackId = $feedback->feedbackId;
$newCustomerFeedback->FeedbackRating = $feedback->feedbackRating;
$newCustomerFeedback->CreatedDate = date(VB_DATE_TIME_FORMAT);
if ($tableObj->save($newCustomerFeedback)) {
$customerFeedbackCounter++;
} else {
$customerFeedbackCounter = 0;
}
}
} catch (Exception $ex) {
$conn->rollback();
return $customerFeedbackCounter;
}
if ($customerFeedbackCounter) {
$conn->commit();
return $customerFeedbackCounter;
}
}
示例10: testWithPreMadeConnection
public function testWithPreMadeConnection()
{
ConnectionManager::config('default', ['className' => 'Cake\\Database\\Connection', 'driver' => 'Cake\\Database\\Driver\\Sqlite']);
$module = new CakeDbModule('default');
$instance = (new Injector($module, $_ENV['TMP_DIR']))->getInstance('Cake\\Database\\Connection');
$this->assertSame(ConnectionManager::get('default'), $instance);
}
示例11: getTotalInvoicesByPo
public function getTotalInvoicesByPo($data)
{
$connection = ConnectionManager::get('default');
$results = $connection->execute('select sum(invoice_users.total) total from invoices,invoice_users where invoices.id=invoice_users.invoice_id and invoices.po_id=' . $data['po_id'])->fetchAll();
$this->log(print_r($results, true), 'debug');
return array('sum' => $results[0][0]);
}
示例12: main
/**
* main
*
*/
public function main()
{
$schemaPo = APP . 'Locale' . DS . 'schema.pot';
$conn = ConnectionManager::get('default');
$collection = $conn->schemaCollection();
$translations = new Translations();
$tables = $collection->listTables();
foreach ($tables as $table) {
$translations->insert($table, Inflector::humanize(Inflector::underscore($table)));
$translations->insert($table, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))));
$columns = $collection->describe($table)->columns();
foreach ($columns as $column) {
$c = $collection->describe($table)->column($column);
$comment = $c['comment'];
$t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore($column)));
$translations[] = $t;
$t->setTranslation($comment);
$t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))) . ' ' . Inflector::humanize(Inflector::underscore($column)));
$translations[] = $t;
$t->setTranslation($comment);
}
}
$poString = $translations->toPoString();
$caked = preg_replace('/msgctxt "([^"]+)"/i', '#: \\1', $poString);
$this->createFile($schemaPo, $caked);
}
示例13: setUp
/**
* setUp
*
* @return void
*/
public function setUp()
{
parent::setUp();
$this->Addresses = TableRegistry::get('Geo.Addresses');
$this->Addresses->addBehavior('Geo.Geocoder', array('real' => false));
$this->db = ConnectionManager::get('test');
}
示例14: install
public function install()
{
$sql = [];
$defaultSql = ['40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT', '40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS', '40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION', '40101 SET NAMES utf8', '40103 SET @OLD_TIME_ZONE=@@TIME_ZONE', '40103 SET TIME_ZONE=\'+00:00\'', '40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0', '40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0', '40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=\'NO_AUTO_VALUE_ON_ZERO\'', '40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0'];
foreach ($defaultSql as $key => $value) {
$sql[] = '/*!' . $value . ' */;';
}
$sql[] = "\n";
$db = ConnectionManager::get('default');
$collection = $db->schemaCollection();
$tables = $collection->listTables();
if (count($tables) > 0) {
foreach ($tables as $key => $value) {
$table = $collection->describe($value)->createSql($db);
$sql[] = '-- Inicio das estrutura da tabela `' . $value . '` --';
$sql[] = '/* !40101 SET character_set_client = utf8 */;';
$sql[] = 'DROP TABLE IF EXISTS `' . $value . '`;';
$sql[] = str_replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS ', $table[0]) . ';';
$sql[] = '-- Fim das estrutura da tabela `' . $value . '` --';
$sql[] = "\n";
}
}
$defaultSql = ['40101 SET SQL_MODE=@OLD_SQL_MODE', '40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS', '40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS', '40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT', '40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS', '40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION', '40111 SET SQL_NOTES=@OLD_SQL_NOTES'];
foreach ($defaultSql as $key => $value) {
$sql[] = '/* !' . $value . ' */;';
}
$sql[] = "\n";
$this->save('kiterp.sql', $sql);
}
示例15: getPlugins
/**
* Get plugin list from database
*/
public static function getPlugins()
{
$conn = ConnectionManager::get('default');
$newQuery = $conn->newQuery();
$plugins = $newQuery->select('*')->from('spider_plugins_plugins')->where(['status' => 1])->order(['weight ASC'])->execute()->fetchAll('assoc');
return $plugins;
}