i try to read a config.php into a php class but can't do it.
I want to load the config only when I really need it and not just import it at the beginning of the program
I searched the internet a lot, but found no explanation.
I'll show you my class, where I read the Config:
<?php declare(strict_types=1);
namespace Mailer\Mailer;
class Mailer
{
private $mailConfigs;
public function __construct()
{
$this->mailConfigs = require __DIR__ . '/../../Config/MailConfiguration.php';
}
/**
* @return mixed
*/
public function getMailConfig()
{
return $this->mailConfigs;
}
}
My index file looks like this:
<?php
use Maier/Mailer;
$mailer = new Mailer();
$mailer->getMailConfig();
var_dump($mailConfiguration);
Unfortunately, this code only gives me errors that it could not find the config.
I then thought that the config dn can only be used in the Mailer.php class, but even then, I only get error messages that he can't find the config:
<?php declare(strict_types=1);
namespace Mailer\Mailer;
class Mailer
{
private $mailConfigs;
public function __construct()
{
$this->mailConfigs = require __DIR__ . '/../../Config/MailConfiguration.php';
}
/**
* @return mixed
*/
public function getMailConfig()
{
$this->mailConfigs;
var_dump($mailConfig);
}
}
btw. my config looks like this:
<?php
$mailConfig = [
'mailSender' => 'wk@someSender.com',
'mailSubject' => 'XXX',
'maxConnections' => 400,
'maxTime' => 600,
'csv' => 'mailaccounts.csv',
];
Can someone help me and explain how I can correctly access the array in the config in oop without reading it globally?
Thanks a lot.
The problem with the code is that you're not actually returning the config in your MailConfiguration.php
. You define it as a variable, which you never use in the constructor.
Instead of storing the config array in a variable in your config file, do:
return [
'mailSender' => 'wk@someSender.com',
'mailSubject' => 'XXX',
'maxConnections' => 400,
'maxTime' => 600,
'csv' => 'mailaccounts.csv',
];
Now the config array will be loaded into $this->mailConfigs
in your constructor.
Then, when you want to use it, just do:
public function getMailConfig()
{
return $this->mailConfigs;
}
since it contains the same array as you returned in the config file.
It's good to build configs so you can load different config files for different environments (prod, staging, local, testing etc). So would suggest that you pass the path to the config file to the constructor. Then you can pass different files for different environments. Example:
public function __construct($configFile)
{
$this->mailConfigs = require $configFile;
}
and when you instantiate the class:
$mailer = new Mailer(__DIR__ . '/../../Config/MailConfiguration.php');
Then you can make the file you're passing in conditional on the current environment.