функция — PHP: я должен передать и вернуть эти переменные?

В настоящее время я работаю над преобразованием моего WIP PHP-приложения в объектно-ориентированную архитектуру, так как я обнаружил, что для моего текущего проекта хорошие методы ООП, вероятно, сделают его намного проще. Немного реорганизовав свой код, я натолкнулся на вопрос, который несколько элементарен, но, увы, я не уверен в ответе.

У меня есть раздел (он же «фрагмент») кода — код, содержащийся в функции «GenerateDBSetObjects ()» первого примера кода — который, я считаю, должен быть помещен в функцию (т. Е. Чем-то вроде подпрограммы) , как указано в первом примере. Я хочу поместить его в отдельный функциональный блок по двум причинам:

  1. Упростить основную часть кода
  2. Создать функцию, которую можно протестировать

Однако это создает проблему. Поскольку моя программа фактически имеет две большие переменные области видимости, поэтому мне нужно будет возвращать два значения одновременно (что не составляет большого труда, так как это общая тема: видеть это). Вопрос, который у меня возник, заключается в следующем: поскольку я реструктурирую свой код объектно-ориентированным способом, может ли быть более эффективный способ сделать это? Что-то, может быть, я не учел? Или лучше просто передать и вернуть переменные?

Поскольку $ NumDBSets и $ DBSets [] в основном являются глобальной областью действия, я не совсем уверен, что мне следует делать здесь.

index.php

После

//-------------------------Primary Vars---------------------------------------//
//Fills $ini with a multi-dimensional, associative array that contains all of the
// parameters listed in DBSearchConfig.ini
$ini = (parse_ini_file("config/DBSearchConfig.ini", true))
or die ("Config file: 'DBSearchCongif.ini' could not be read or found in the config folder. Please contact the system administrator");
$LogFile = $ini['SystemVars']['LogFile']; //Assign $LogFile to the location of the system's specific log file found in the .ini
$NumDBSets = 0;//An integer which stores the number of Database sets used by the program.
$DBSets = array(); //Creates an empty array that will store each of the DatabaseSet Objects. Each of the
//Database Sets holds an array of SQL database connection parameters (ie.
//Hostname, Username, etc.), as well as an array of links to the SQL databases within the dataset, et. al.
//For more info see 'DatabaseSet.php'

$CurrDBSetNum = $ini['SystemVars']['DefaultDBSet']; //Get the current DBSet Number from config.
$CurrentConnectionManager = new ConnectionManager;

GenerateDBSetObjects($DBSets, $NumDBSets);//-------------------------FUNCTIONS----------------------------------------//

function GenerateDBSetObjects(){
//Create, Fill and Assign DatabaseSet Objects. Figure out the number of Database sets.
array_push($DBSets, new DatabaseSet);//Push an empty DatabaseSet object into the list to occupy the '0' index!!!
foreach($ini['Databases'] as $ConnectInfoList){
$NumDBSets ++;
//Create a new DatabaseSet Object for this DB Set!!
$newDBSetObject = new DatabaseSet;
$newDBSetObject->ConnectionInfoList = $ConnectInfoList;
$newDBSetObject->CalculateDBSetFields();
array_push($DBSets, $newDBSetObject);

}
}

VS.

До

//-------------------------Primary Vars---------------------------------------//
//Fills $ini with a multi-dimensional, associative array that contains all of the
// parameters listed in DBSearchConfig.ini
$ini = (parse_ini_file("config/DBSearchConfig.ini", true))
or die ("Config file: 'DBSearchCongif.ini' could not be read or found in the config folder. Please contact the system administrator");
$LogFile = $ini['SystemVars']['LogFile']; //Assign $LogFile to the location of the system's specific log file found in the .ini
$NumDBSets = 0;//An integer which stores the number of Database sets used by the program.
$DBSets = array(); //Creates an empty array that will store each of the DatabaseSet Objects. Each of the
//Database Sets holds an array of SQL database connection parameters (ie.
//Hostname, Username, etc.), as well as an array of links to the SQL databases within the dataset, et. al.
//For more info see 'DatabaseSet.php'

$CurrDBSetNum = $ini['SystemVars']['DefaultDBSet']; //Get the current DBSet Number from config.
$CurrentConnectionManager = new ConnectionManager;

//Create, Fill and Assign DatabaseSet Objects. Figure out the number of Database sets.
array_push($DBSets, new DatabaseSet);//Push an empty DatabaseSet object into the list to occupy the '0' index!!!
foreach($ini['Databases'] as $ConnectInfoList){
$NumDBSets ++;
//Create a new DatabaseSet Object for this DB Set!!
$newDBSetObject = new DatabaseSet;
$newDBSetObject->ConnectionInfoList = $ConnectInfoList;
$newDBSetObject->CalculateDBSetFields();
array_push($DBSets, $newDBSetObject);
}

2

Решение

Если вы решили использовать подход с ООП — подумайте о создании класса, который будет отвечать за генерацию и хранение DatabaseSet объекты.
Если объект ConnectionManager класс необходим для генерации DatabaseSets, пометьте его как внедрение зависимостей.
Учебный класс DatabaseSet должен быть объявлен в отдельном файле: DatabaseSet.php,
Давайте назовем наш решающий класс DatabaseSetAdapter:

require_once("DatabaseSet.php");

class DatabaseSetAdapter
{
private $config;
private $logFile;
private $NumDBSets = 0;
private $DBSets = [];
private $connManager;
private $currDBSetNum;

public function __construct($iniFilePath, ConnectionManager $manager)
{
$this->config = (parse_ini_file($iniFilePath, true))
or die ("Config file: 'DBSearchCongif.ini' could not be read or found in the config folder. Please contact the system administrator");

$this->logFile = $this->config['SystemVars']['LogFile'];
$this->connManager = $manager;
$this->currDBSetNum = $this->config['SystemVars']['DefaultDBSet'];
}

public function generateDBSetObjects()
{
//Create, Fill and Assign DatabaseSet Objects. Figure out the number of Database sets.
$this->DBSets[] = new DatabaseSet;  //Push an empty DatabaseSet object into the list to occupy the '0' index!!!
foreach($this->config['Databases'] as $connectInfoList){

//Create a new DatabaseSet Object for this DB Set!!
$newDBSetObject = new DatabaseSet;
$newDBSetObject->ConnectionInfoList = $connectInfoList;
$newDBSetObject->CalculateDBSetFields();
$this->DBSets[] = $newDBSetObject;
$this->NumDBSets++;
}
}

public function getNumDBSets()   // a privileged method
{
return $this->NumDBSets;
}

}

// using of DatabaseSetAdapter:
$dbsetAdapter = new DatabaseSetAdapter("config/DBSearchConfig.ini", new ConnectionManager);
$dbsetAdapter->generateDBSetObjects();
$numDbSets = $dbsetAdapter->getNumDBSets();
....
2

Другие решения

Глобальный охват и ООП не подходят друг другу.

У вас должен быть объект, хранящий эту информацию

class DBSets {
private $num;
private $data;

function __construct() {
$this->num = 0;
$this->data = [];
}

//setters and getters for accessing private properties
}

Если $ num хранит только количество элементов в $ data, вы можете удалить его и использовать

count($this->data);
1