Note that there are some explanatory texts on larger screens.

plurals
  1. POZend Framework 2 module share variables between controllers onBootstrap
    primarykey
    data
    text
    <p>Is it possible to create variables or even shared objects (like DB adapter) at in Module.php for use in all view controllers? (Zend Framework 2)</p> <p>For example:</p> <pre><code>class Module { public function onBootstrap(MvcEvent $e) { $moduleConfig = $e-&gt;getServiceManager()-&gt;get('Config') } } </code></pre> <p>And in a controller, somehow access using:</p> <pre><code>$this-&gt;moduleConfig['db'] </code></pre> <p>In above I know that would just be the config array for the db adapter, but how would that even work?</p> <p>I see that one can do this in a controller action:</p> <pre><code>$config = $this-&gt;getServiceLocator()-&gt;get('Config') $dba = new DbAdapter($config['db']); </code></pre> <p>I don't want to do that every place I need my config. How could I make it something like: $this->config ?? So its available to all actions. Even better, how to do that in the entire Module? I know I am going about this all wrong, but in ZF1 we had Zend_Registry::get() for simple things like this. I am reading over the docs and all sorts of tuts out there, but always there's some assumptions being made and I just get lost. So all I really want is : A) A Globally accessible config item, B) A globally accessible db adapter</p> <p>I just want to call on $this->db or $this->config->item in my controllers. Is this possible? I know I am missing something totally simple.</p> <p>Also I did try setting $this->config in my __construct using $this->getServiceLocator()->get('Config'); But I understand that service locator is not available yet during construct. I tried doing similar by setting up a preDispatch in the onBootstrap of the module, but I can't seem to get those items into my controllers.</p> <p>FYI, I do have this in my global.php (and no, its not staying there, just example):</p> <pre><code>'db' =&gt; array( 'driver' =&gt; 'Pdo', 'dsn' =&gt; 'mysql:dbname=mydb;host=localhost;', 'username' =&gt; 'root', 'password' =&gt; '', 'driver_options' =&gt; array( PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES \'UTF8\'' ), ), </code></pre> <p>I am able to access that and other items in any action using getServiceLocator(). I'd like those items to be available as my controller properties as in $this->config->item. </p> <p>I appreciate any guidance! Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload