Skip to content

Commit

Permalink
New template customDBConnection
Browse files Browse the repository at this point in the history
  • Loading branch information
jalogut committed Apr 3, 2017
1 parent 931b096 commit 8954fd1
Show file tree
Hide file tree
Showing 6 changed files with 266 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1. Add the database tables setup:

${Vendorname}\${Modulename}\Setup\${Connectionname}DatabaseSetup::getTablesToCreate();
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generate code needed to setup a new Database Connection
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/**
* ${Connectionname}DatabaseSetup
*
* @copyright Copyright © ${commentsYear} ${CommentsCompanyName}. All rights reserved.
* @author ${commentsUserEmail}
*/

namespace ${Vendorname}\${Modulename}\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\SchemaSetupInterface;
use ${Vendorname}\${Modulename}\Setup\ConfigOptionsList as ${Modulename}SetupConfig;

class ${Connectionname}DatabaseSetup
{

protected $connection;

public function __construct(SchemaSetupInterface $setup)
{
$this->connection = $setup->getConnection(${Modulename}SetupConfig::DB_CONNECTION_NAME);
}

public function setupTables()
{
$tablesToCreate = $this->getTablesToCreate();
$this->createTables($tablesToCreate);
}

/**
* @return Table[]
*/
protected function getTablesToCreate() : array
{
$tables = [];
// $tables[] = $this->connection
// ->newTable($this->connection->getTableName('some_table_name'))
// ->addColumn('id', Table::TYPE_INTEGER, 11, ['nullable' => false, 'primary' => true])
// ->addColumn('name', Table::TYPE_TEXT, 255, ['nullable' => false]);

return $tables;
}

protected function createTables(array $tables)
{
foreach ($tables as $table) {
$this->dropTableIfExists($table->getName());
$this->connection->createTable($table);
}
}

protected function dropTableIfExists(string $tableName)
{
if ($this->connection->isTableExists($this->connection->getTableName($tableName))) {
$this->connection->dropTable($this->connection->getTableName($tableName));
}
}
}
157 changes: 157 additions & 0 deletions templates/customDBConnection/Setup/ConfigOptionsList.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
<?php
/**
* ConfigOptionsList
*
* @copyright Copyright © ${commentsYear} ${CommentsCompanyName}. All rights reserved.
* @author ${commentsUserEmail}
*/

namespace ${Vendorname}\${Modulename}\Setup;

use Magento\Framework\Config\Data\ConfigData;
use Magento\Framework\Config\File\ConfigFilePool;
use Magento\Framework\Setup\ConfigOptionsListInterface;
use Magento\Framework\Setup\Option\TextConfigOption;
use Magento\Framework\App\DeploymentConfig;
use Magento\Framework\Config\ConfigOptionsListConstants;
use Magento\Setup\Model\ConfigGenerator;
use Magento\Setup\Validator\DbValidator;
use Zend\ServiceManager\Di\DiAbstractServiceFactory;
use Zend\ServiceManager\ServiceManager;

class ConfigOptionsList implements ConfigOptionsListInterface
{
const DB_CONNECTION_NAME = '${connectionname}';
const CONFIG_PATH_DB_CONNECTION = ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTIONS . '/' . self::DB_CONNECTION_NAME;
const OPTION_DB_HOST = self::DB_CONNECTION_NAME . '-db-host';
const OPTION_DB_NAME = self::DB_CONNECTION_NAME . '-db-name';
const OPTION_DB_USER = self::DB_CONNECTION_NAME . '-db-user';
const OPTION_DB_PASSWORD = self::DB_CONNECTION_NAME . '-db-password';
const OPTION_DB_ENGINE = self::DB_CONNECTION_NAME . '-db-engine';
const OPTION_DB_INIT_STATEMENTS = self::DB_CONNECTION_NAME . '-db-init-statements';

const OPTIONAL_OPTIONS = [
ConfigOptionsListConstants::KEY_HOST => self::OPTION_DB_HOST,
ConfigOptionsListConstants::KEY_NAME => self::OPTION_DB_NAME,
ConfigOptionsListConstants::KEY_USER => self::OPTION_DB_USER,
ConfigOptionsListConstants::KEY_PASSWORD => self::OPTION_DB_PASSWORD,
ConfigOptionsListConstants::KEY_ENGINE => self::OPTION_DB_ENGINE,
ConfigOptionsListConstants::KEY_INIT_STATEMENTS => self::OPTION_DB_INIT_STATEMENTS,
];

protected $configGenerator;
protected $dbValidator;

public function __construct(
ConfigGenerator $configGenerator,
DbValidator $dbValidator,
ServiceManager $serviceLocator,
DiAbstractServiceFactory $abstractServiceFactory
) {
$this->configGenerator = $configGenerator;
$this->dbValidator = $dbValidator;
$this->fixDBValidatorErrorGettingInstanceOfLoggerQuiet($serviceLocator, $abstractServiceFactory);
}

protected function fixDBValidatorErrorGettingInstanceOfLoggerQuiet(
ServiceManager $serviceLocator,
DiAbstractServiceFactory $abstractServiceFactory
) {
$serviceLocator->addAbstractFactory($abstractServiceFactory);
}

public function getOptions()
{
return [
new TextConfigOption(
self::OPTION_DB_HOST,
TextConfigOption::FRONTEND_WIZARD_TEXT,
self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_HOST,
'Database host (Connection name: ${Connectionname})',
'localhost'
),
new TextConfigOption(
self::OPTION_DB_NAME,
TextConfigOption::FRONTEND_WIZARD_TEXT,
self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_NAME,
'Database name (Connection name: ${Connectionname})',
'magento2_${connectionname}'
),
new TextConfigOption(
self::OPTION_DB_USER,
TextConfigOption::FRONTEND_WIZARD_TEXT,
self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_USER,
'Database username (Connection name: ${Connectionname})',
'root'
),
new TextConfigOption(
self::OPTION_DB_PASSWORD,
TextConfigOption::FRONTEND_WIZARD_PASSWORD,
self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_PASSWORD,
'Database password (Connection name: ${Connectionname})',
''
),
new TextConfigOption(
self::OPTION_DB_ENGINE,
TextConfigOption::FRONTEND_WIZARD_TEXT,
self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_ENGINE,
'Database engine (Connection name: ${Connectionname})',
'innodb'
),
new TextConfigOption(
self::OPTION_DB_INIT_STATEMENTS,
TextConfigOption::FRONTEND_WIZARD_TEXT,
self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_INIT_STATEMENTS,
'Database initial set of commands (Connection name: ${Connectionname})',
'SET NAMES utf8;'
),
];
}

public function createConfig(array $data, DeploymentConfig $deploymentConfig)
{
$configData = new ConfigData(ConfigFilePool::APP_ENV);

foreach (self::OPTIONAL_OPTIONS as $configSubPath => $option) {
if (isset($data[$option])) {
$configData->set(
self::CONFIG_PATH_DB_CONNECTION . '/' . $configSubPath,
$data[$option]
);
}
}
$activeConfigPath = self::CONFIG_PATH_DB_CONNECTION . '/' . ConfigOptionsListConstants::KEY_ACTIVE;
if ($deploymentConfig->get($activeConfigPath) === null) {
$configData->set($activeConfigPath, '1');
}

return [$configData];
}

/**
* @param array $options
* @param DeploymentConfig $deploymentConfig
* @return array
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function validate(array $options, DeploymentConfig $deploymentConfig) //@codingStandardsIgnoreLine
{
if (!$options[ConfigOptionsListConstants::INPUT_KEY_SKIP_DB_VALIDATION]) {
try {
$this->dbValidator->checkDatabaseConnection(
$options[self::OPTION_DB_NAME],
$options[self::OPTION_DB_HOST],
$options[self::OPTION_DB_USER],
$options[self::OPTION_DB_PASSWORD]
);
} catch (\Exception $e) {
$errors = [
sprintf('Error validating DB connection name: "%s"', self::DB_CONNECTION_NAME),
$e->getMessage()
];
return $errors;
}
}
return [];
}
}
40 changes: 40 additions & 0 deletions templates/customDBConnection/Setup/InstallSchema.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* InstallSchema
*
* @copyright Copyright © ${commentsYear} ${CommentsCompanyName}. All rights reserved.
* @author ${commentsUserEmail}
*/
namespace ${Vendorname}\${Modulename}\Setup;

use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use ${Vendorname}\${Modulename}\Setup\${Connectionname}DatabaseSetupFactory;

/**
* Upgrade the Catalog module DB scheme
*/
class InstallSchema implements InstallSchemaInterface
{
protected $${connectionname}DatabaseSetupFactory;

public function __construct(${Connectionname}DatabaseSetupFactory $${connectionname}DatabaseSetupFactory)
{
$this->${connectionname}DatabaseSetupFactory = $${connectionname}DatabaseSetupFactory;
}

/**
* {@inheritdoc}
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) //@codingStandardsIgnoreLine
{
$setup->startSetup();

$${connectionname}DatabaseSetup = $this->${connectionname}DatabaseSetupFactory->create(['setup' => $setup]);
$${connectionname}DatabaseSetup->setupTables($setup);

$setup->endSetup();
}
}
6 changes: 6 additions & 0 deletions templates/customDBConnection/etc/di.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!-- FIX issue when creating new instances of Magento\Setup\Validator\DbValidator as Magento forgot to add this preference -->
<preference for="Zend\ServiceManager\ServiceLocatorInterface" type="Zend\ServiceManager\ServiceManager"/>
<!-- End fix -->
</config>

0 comments on commit 8954fd1

Please sign in to comment.