/*
Raw code pastes from my post at:
http://www.1stbyte.com/2013/01/03/zend-framework-2-global-database-adapter-object-and-config-variables/
*/
# config/autoload/things.config.local.php
return array(
'things' => array(
'avalue' => 'avalue1',
'boolvalue' => true,
),
);
# calling things, assuming $this->things is defined in preDispatch below:
$this->config['things']['boolvalue'];
# or, also with creating instance in the action:
$config = $this->getServiceLocator()->get('Config');
echo $config['things']['boolvalue'];
#2 getting access to service manager config:
$this->getServiceLocator()->get('Config');
# add controller action class method:
protected function attachDefaultListeners()
{
parent::attachDefaultListeners();
$events = $this->getEventManager();
$this->events->attach('dispatch', array($this, 'preDispatch'), 100);
$this->events->attach('dispatch', array($this, 'postDispatch'), -100);
}
# and the pre and post methods for dispatch above
public function preDispatch (MvcEvent $e)
{
// this is a db convenience class I setup in global.php
// under the service_manager factories (will show below)
$this->db = $this->getServiceLocator()->get('FBDb');
// this is just standard config loaded from ServiceManager
// set your property in your class for $config (protected $config;)
// then have access in entire controller
$this->config = $this->getServiceLocator()->get('Config');
// this comes from the things.config.local.php file
echo "things boolvalue: " . $this->config['things']['boolvalue'];
}
public function postDispatch (MvcEvent $e)
{
// Called after actions
}
# 3 in the global.php config array for service_manager and db adapter access
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=mydb;host=localhost;',
'username' => 'root',
'password' => '',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
'db-adapter' => function($sm) {
$config = $sm->get('config');
$config = $config['db'];
$dbAdapter = new Zend\Db\Adapter\Adapter($config);
return $dbAdapter;
},
'FBDb' => function($sm) {
$dba= $sm->get('db-adapter');
$db = new FBDb\Db($dba);
return $db;
},
),
),
#using the preDispatch above we have this line:
$this->db = $this->getServiceLocator()->get('FBDb');
# when we want to call up a query and return a record set:
$sql = 'select * from customer where cust_nbr between ? and ?';
$rs = $this->db->fetchAll($sql, array('120400', '125250'));