Zend DB Introduction

Laminas\Db Introduction — (Zend Framework / Laminas)

laminas/laminas-db is a lightweight database abstraction layer used within Laminas (formerly Zend Framework). It provides tools to interact with SQL databases in a flexible and structured way without using a full ORM like Doctrine.


Why Use laminas-db?

Feature

Description

Lightweight

Doesn’t come with the overhead of a full ORM.

SQL Abstraction

Helps you write platform-independent SQL.

TableGateway, ResultSet, SQL

Structured components for querying, inserting, updating, etc.

Integration

Easily integrates with Laminas MVC or standalone apps.


1. Installation

Make sure you have Laminas DB component installed:

composer require laminas/laminas-db

2. Configure DB Connection (config/autoload/global.php)

Add database config

use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Adapter\AdapterServiceFactory;

return [
    'db' => [
        'driver'   => 'Pdo_Mysql',
        'hostname' => '127.0.0.1',
        'database' => 'zend',
        'username' => 'root',
        'password' => '',
        'charset'  => 'utf8mb4',
    ],
    'service_manager' => [
        'factories' => [
            Adapter::class => AdapterServiceFactory::class,
        ],
    ],
];

Replace your_database_name, your_db_user, and your_db_password with actual credentials.


3. Configure Adapter (module/Application/config/module.config.php)

'controllers' => [
  'factories' => [
    Controller\YourController::class => function($container) {
      $dbAdapter = $container->get(Adapter::class);
      return new Controller\YourController($dbAdapter);
    },
  ],
],



4. Inject Adapter into Your Controller

In your controller constructor:

use Laminas\Db\Adapter\Adapter;

class YourController extends AbstractActionController
{
  private $dbAdapter;

  public function __construct(Adapter $dbAdapter)
  {
    $this->dbAdapter = $dbAdapter;
  }
}



4. Run a Query

You can use Adapter directly to run raw SQL:

public function indexAction()
{
  $sql = 'SELECT * FROM users WHERE id > ?';
  $result = $this->dbAdapter->query($sql, [0]);

  foreach ($result as $row) {
    print_r($row); // Output row as array
  }

  return false; // To stop rendering
}



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.