Search code examples
global-variableszend-framework2zend-config

How to use Zend\Config (application wide variables)


Main question is self explanatory, but I'll give some side examples:

  • I'm having trouble figuring out databases, though it seems I can work out config with ServiceManager stuff

  • I want to use constants for cookie names, so I can change them easily if there are collisions. Current, I'm calling $config = new \Zend\Config\Config(include $_SERVER['DOCUMENT_ROOT'] . '/../config.php'); every time I want access to my global config.php file. A lot of previous solutions were in Zend 1 (eg Zend_Registry). Is this the right way to do it? It seems a little unwieldy using that over and over.

  • Is there a way to utilize a Module's configuration file to set module-wide-variables/constants?

  • Unless I'm completely missing it, there's no application.ini in Zend 2

  • Storing recaptcha public/private keys

  • I'm also using my config file for session-variables (same idea as $_SESSION[CONST_NAME]), which makes it really clumsy with the config file above. Is it better to hardcode the session names? Like:


$container = new Zend\Session\Container('auth');
$container->offsetSet('user', $user);
... // instead of 
$container = new Zend\Zession\Container($config['auth']['containername']);
$container->offsetSet($config['auth']['user'], $user);

Solution

  • All configuration from each module.config.php or Module.php are put together into a big pot. You can easily access those via $this->getServiceLocator()->get('config')

    When it comes down to constants, they should be placed inside the respective classes. Like

    class UserStorage {
        const SESSIONCONTAINERNAME = 'blubbusersession';
    }
    

    That way you can call \My\User\Model\UserStorage::SESSIONCONTAINERNAME whenever you need this info

    As far as your example is concerned thought, there should be almost no need to var-code your session-container-name because the information from your modules session-data should be made available via your modules Service-Classes. But if you still need it, see aboves example.

    Furthermore i think it may be a good idea for you to check out how zf-commons\ZfcUser does things