Start on project with the connection services and first command to list databases
This commit is contained in:
38
src/Console/ListDatabasesCommand.php
Normal file
38
src/Console/ListDatabasesCommand.php
Normal file
@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use App\Service\DatabaseManager;
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Input\InputInterface;
|
||||
use Symfony\Component\Console\Output\OutputInterface;
|
||||
|
||||
class ListDatabasesCommand extends Command
|
||||
{
|
||||
// the name of the command (the part after "bin/console")
|
||||
protected static $defaultName = 'app:db:list';
|
||||
|
||||
public function __construct(
|
||||
private DatabaseManager $db,
|
||||
)
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
protected function configure(): void
|
||||
{
|
||||
// ...
|
||||
}
|
||||
|
||||
protected function execute(InputInterface $input, OutputInterface $output): int
|
||||
{
|
||||
$dbs = $this->db->listDatabases();
|
||||
|
||||
$output->writeln('List of databases:');
|
||||
foreach ($dbs as $db) {
|
||||
$output->writeln(sprintf(' -%s', $db));
|
||||
}
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
28
src/Service/DatabaseManager.php
Normal file
28
src/Service/DatabaseManager.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use mysqli;
|
||||
|
||||
class DatabaseManager
|
||||
{
|
||||
private mysqli $conn;
|
||||
|
||||
public function __construct(
|
||||
private MysqliConnection $service
|
||||
)
|
||||
{
|
||||
$this->conn = $this->service->getConnection();
|
||||
}
|
||||
|
||||
public function listDatabases(): array
|
||||
{
|
||||
$dbs = [];
|
||||
$results = $this->conn->query('SHOW DATABASES');
|
||||
while ($result = $results->fetch_object()) {
|
||||
$dbs[] = $result->Database;
|
||||
}
|
||||
|
||||
return $dbs;
|
||||
}
|
||||
}
|
23
src/Service/MysqliConnection.php
Normal file
23
src/Service/MysqliConnection.php
Normal file
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use mysqli;
|
||||
|
||||
class MysqliConnection
|
||||
{
|
||||
private mysqli $connection;
|
||||
|
||||
public function __construct($hostname, $user, $password)
|
||||
{
|
||||
$this->connection = new mysqli($hostname, $user, $password);
|
||||
if ($this->connection->connect_error) {
|
||||
throw new \Exception("Connection failed: " . $this->connection->connect_error);
|
||||
}
|
||||
}
|
||||
|
||||
public function getConnection(): mysqli
|
||||
{
|
||||
return $this->connection;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user