Zend Framework 2 Access DB from Custom Library

145 Views Asked by At

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.

2

There are 2 best solutions below

0
Prasad Rajapaksha On BEST ANSWER

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);
    }

}
0
marcosh On

An approach could be using a factory.

You create a class UserFactory implementing Zend\ServiceManager\FactoryInterface. This class will have a method createService with a $serviceLocator parameter. You use this service locator to retrieve your dependencies and pass them to your User class.

In your User class you need to use a controller that accepts as parameters the dependencies that you need to pass to it