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

app_name, version, timezone

In controller or service for app metadata

.ini, .json, .php

Database Connection

db.host, db.user, db.pass

Used to connect via Laminas\Db\Adapter

.php, .ini, .json

Mail Configuration

mail.host, port, username

Used in MailService (PHPMailer, etc.)

.php, .ini


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.