Я использую один файл XML для хранения настроек конфигурации для нескольких объектов. Например:
<config>
<database>
<user>myuser</user>
</database>
<application>
<component1>mycomponent</component1>
</application>
<infrastructure>
<hostname1>server1</hostname1>
</infrastructure>
</config>
Я хочу, чтобы каждый из моих объектов обращался к различным аспектам xml; например, класс базы данных будет обращаться к элементу базы данных.
Какой метод можно использовать для быстрого доступа к этой конфигурации через мои объекты без воспроизведения кода?
Вы можете создать объект Config
который считывает конфигурацию из XML файла, а затем использовать Configurable
признак в классах, которые вы хотите "автоматически" настроить из XML (см. Пример ниже).
config.xml:
<config>
<database>
<user>myuser</user>
</database>
<application>
<component1>mycomponent</component1>
</application>
<infrastructure>
<hostname1>server1</hostname1>
</infrastructure>
</config>
PHP-код:
class Config
{
/**
* Full XML configuration
*
* @var SimpleXMLElement
*/
private static $xml;
/**
* Parse XML configuration file into XML object (once)
*/
public function __construct()
{
if (!self::$xml) {
$xmlSource = file_get_contents('config.xml');
self::$xml = new SimpleXMLElement($xmlSource);
}
}
/**
* Returns the first node matching the specified xpath
*
* @param $xpath
*
* @return SimpleXMLElement
*/
public function getFirstByXpath($xpath)
{
// Return the first matching configuration
return self::$xml->xpath($xpath)[0];
}
}
trait Configurable
{
/**
* Class configuration XML element
*
* @var SimpleXMLElement
*/
private $configuration;
/**
* Get the class configuration XML element
*
* @return SimpleXMLElement
*/
function getConfiguration()
{
if (!$this->configuration) {
$tag = strtolower(get_class($this));
$xpath = '/config/' . $tag;
$this->configuration = (new Config())->getFirstByXpath($xpath);
}
return $this->configuration;
}
}
class application
{
use configurable;
}
class database
{
use configurable;
}
$app = new application();
echo "App component 1: ", $app->getConfiguration()->component1, PHP_EOL;
$db = new database();
echo "DB user: ", $db->getConfiguration()->user, PHP_EOL;
Вывод:
App component 1: mycomponent
DB user: myuser