本文整理汇总了PHP中Cake\Datasource\ConnectionManager类的典型用法代码示例。如果您正苦于以下问题:PHP ConnectionManager类的具体用法?PHP ConnectionManager怎么用?PHP ConnectionManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConnectionManager类的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: 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;
}
示例3: 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);
}
示例4: save
public function save()
{
if ($this->request->is('post')) {
$attemptId = $this->request->data['attemptId'];
$token = $this->request->data['token'];
$rawSamples = $this->request->data['samples'];
$happiness = $this->request->data['happiness'];
$this->infolog("Samples Save attempted. Attempt: " . $attemptId . "; Happiness: " . $happiness . "; Samples: " . serialize($rawSamples));
if ($attemptId && $token && $rawSamples && $this->Samples->Attempts->checkUserAttempt($this->Auth->user('id'), $attemptId, $token)) {
$attempt = $this->Samples->Attempts->get($attemptId);
//Get attempt, for saving happiness and identifying whether report has been submitted
$samples = [];
foreach ($rawSamples as $siteId => $schools) {
foreach ($schools as $schoolId => $children) {
foreach ($children as $childId => $types) {
foreach ($types as $typeId => $value) {
if ($value) {
$sample = ['attempt_id' => $attemptId, 'site_id' => $siteId, 'school_id' => $schoolId, 'child_id' => $childId, 'sample_stage_id' => $typeId, 'before_submit' => !$attempt->report];
array_push($samples, $sample);
}
}
}
}
}
//Note: Always create new entry - should never already be saved entries
$samplesData = $this->Samples->newEntities($samples);
if (!is_null($happiness)) {
$attempt->happiness = $happiness;
$attempt->sampling = true;
} else {
$attempt = null;
}
$connection = ConnectionManager::get('default');
$connection->transactional(function () use($samplesData, $attempt, $attemptId) {
foreach ($samplesData as $sample) {
if (!$this->Samples->save($sample)) {
$this->set('status', 'failed');
$this->infolog("Samples Save failed Attempt: " . $attemptId);
return false;
}
}
if (!is_null($attempt) && !$this->Samples->Attempts->save($attempt)) {
$this->set('status', 'failed');
$this->infolog("Samples Save failed Attempt: " . $attemptId);
return false;
}
$this->set('status', 'success');
$this->infolog("Samples Save succeeded. Attempt: " . $attemptId);
});
} else {
$this->set('status', 'denied');
$this->infolog("Samples Save denied. Attempt: " . $attemptId);
}
} else {
$this->set('status', 'notpost');
$this->infolog("Samples Save not POST ");
}
$this->viewBuilder()->layout('ajax');
$this->render('/Element/ajaxmessage');
}
示例5: 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];
}
示例6: 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));
}
}
示例7: tearDownAfterClass
/**
* Purge ConnectionManager configs.
*
* @return void
*/
public static function tearDownAfterClass()
{
foreach (self::$datasources as $ds => $configs) {
\Cake\Datasource\ConnectionManager::drop($ds);
}
\Cake\Utility\Security::salt('');
}
示例8: setUp
/**
* setup
*
* @return void
*/
public function setUp()
{
parent::setUp();
$this->connection = ConnectionManager::get('test');
$this->table = new Table(['table' => 'articles', 'connection' => $this->connection]);
$this->fixtureData = [['id' => 1, 'author_id' => 1, 'title' => 'First Article', 'body' => 'First Article Body', 'published' => 'Y'], ['id' => 2, 'author_id' => 3, 'title' => 'Second Article', 'body' => 'Second Article Body', 'published' => 'Y'], ['id' => 3, 'author_id' => 1, 'title' => 'Third Article', 'body' => 'Third Article Body', 'published' => 'Y']];
}
示例9: 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')]);
//}
}
示例10: 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']);
}
示例11: 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']);
}
}
示例12: 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);
}
示例13: 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;
}
}
示例14: 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);
}
示例15: 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]);
}