Advertisement
Google Ad Slot: content-top
Zend Config
What is Zend Config?
Zend Config is a component to read, write, and merge configuration data from various sources like PHP arrays, INI, JSON, or XML files.
It gives you a structured, object-like interface to access configuration settings.
Key Features
- Supports PHP arrays,
.ini,.json,.xml - Access config like an object (
$config->db->host) - Supports readonly and modifiable modes
- Easily merge multiple configurations
Basic Example (Using PHP Array)
Step 1: Create file in (config/config.php)
<?php return [ 'name' => 'John', 'db' => [ 'host' => 'localhost', 'user' => 'root', 'password' => 'secret', ], ];
Step 2: Load Config in Code (module\Application\src\Controller\MainController.php)
use Laminas\Config\Factory;
class MainController extends AbstractActionController
{
public function homeAction()
{
$config = Factory::fromFile('config/config.php', true);
// Access values
echo $config->name;
echo $config->db->host; // localhost
echo $config->db->user; // root
return new ViewModel();
}
}
Supported File Formats & Demo
1. PHP Config
File: (config/config.php)
<?php return [ 'name' => 'John', 'db' => [ 'host' => 'localhost', 'user' => 'root', 'password' => 'secret', ], ];
2. INI Config
File:(config/config.ini)
name = "John" [db] host = "localhost" user = "root" pass = "secret"
3. JSON Config
File: (config/config.json)
{
"name": "John",
"db": {
"host": "localhost",
"user": "root",
"pass": "secret"
}
}
4. XML Config
File: (config/config.xml)
<config> <name>John</name> <db> <host>localhost</host> <user>root</user> <pass>secret</pass> </db> </config>
Merging Multiple Config Files
$config1 = [ 'app' => ['name' => 'MyApp', 'debug' => false] ]; $config2 = [ 'app' => ['debug' => true] ]; use Laminas\Config\Config; $conf1 = new Config($config1, true); $conf2 = new Config($config2, true); $conf1->merge($conf2); echo $conf1->app->debug; // true
Real-World Usage of Laminas\Config
Use Case |
Example Config File |
Used In |
Config Format |
|---|---|---|---|
Application Settings |
|
In controller or service for app metadata |
|
Database Connection |
|
Used to connect via |
|
Mail Configuration |
|
Used in MailService (PHPMailer, etc.) |
|