Search code examples
phpzend-frameworkzend-framework2zend-dbzend-db-table

Zend Framework 2 Access DB from Custom Library


I am migrating a project from Zend framework 1.4 to 2.4, I have a class in "vendor/custom/classes/User.php"

<?php

namespace Classes;

use Zend\Db\TableGateway\TableGateway;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Db\Adapter\Adapter;

class User 
{
    public function getItemById($id)
    {
        //$config = $this->getServiceLocator()->get('config');
        //This only work in controller
        $configs = array();
        $adapter = new Adapter($configs);


        $projectTable = new TableGateway('project', $adapter);
        $rowset = $projectTable->select(array('type' => 'PHP'));

        echo 'Projects of type PHP: ';
        foreach ($rowset as $projectRow) {
             echo $projectRow['name'] . PHP_EOL;
        }
    }
}

?>  

I need to load merged configurations in my files in "config/autoload" , global.php and local.php. $config = $this->getServiceLocator()->get('config'); Can someone guide me how can I get these configurations from a custom class. Basically I am trying to do is writing set of classes like User, Project, Customer outside of Models and use them commonly in all modules like CMS, Admin Panel, Web site. Appreciate your guidance.


Solution

  • Since there is no direct way to access those configurations. I have wrote constants with DB access information in the local and global php files in config/autoload and used it in my class.

    class DBManager 
    {
        protected $adapter ;
        protected $connection ;
    
        /** 
        * Constructor 
        */ 
        public function __construct() 
        {
            $configs = array(
                'hostname' => DB_SERVER_NAME,
                'driver' => 'Pdo_Mysql',
                'database' => DB_DATABASE_NAME,
                'username' => DB_USER_NAME,
                'password' => DB_PASSWORD ,
             );
    
            $this->adapter = new Adapter($configs);
        }
    
    }