user2367458
user2367458

Reputation: 91

zend framework 2 constants

I have to declare constants which are available anywhere in application. In Zend Framework 1 we used to declare in application.ini as :

constants.NAME_TITLE = "User Name",

Where and how do we do this in Zend Framework 2 ?

Upvotes: 8

Views: 5802

Answers (4)

Rizban Ahmad
Rizban Ahmad

Reputation: 139

You can define, assign and access CONSTANT as follows: Use these two classes with alias:

use Zend\Config\Config as Zend_Config;
use Zend\Config\Processor\Constant as Zend_Constant;

And then use below code to your any function of the controller class:

define ('TEST_CONST', 'bar');
// set true to Zend\Config\Config to allow modifications
$config = new Zend_Config(array('foo' => 'TEST_CONST'), true);
$processor = new Zend_Constant();
$processor->process($config);
echo $config->foo;

It will give o/p:

bar

Upvotes: 0

Maulik Patel
Maulik Patel

Reputation: 670

For Zend Framework 2, one alternative solution.

you can define your global variable inside config/autoload/local.php

 'array_name' => array(
      'variable_name' => value,
 ),

and use it anywhere just like :

$this->config = $obj->getServiceLocator()->get('config'); //create config object
$this->you_variable = $this->config['arrayname']['variable_name']; // fetch value
echo $this->you_variable; // print value

Upvotes: 2

Black
Black

Reputation: 10397

I have found solution here. You have to create storage class in Model. In that class you can create as many constants as you want.

<?php  
namespace Application\Model;
class Application {
    const EMAIL = '[email protected]';
}

Now it can be accessed everywhere by:

NameOfModule\Model\NameOfModel::NAMEOFCONSTANT

So you can for example print the constant in a view like this:

<?php echo Application\Model\Application::EMAIL; ?>

Upvotes: 9

Md Mehedi Hasan
Md Mehedi Hasan

Reputation: 1792

You can also write function and variable that can be accessed any where of your application like controller,model and views.

<?php  
namespace Webapp;

class ControllerName
   {
        const EMAIL     = '[email protected]';

        public static function myFunction()
          {
             echo "doing work well.";
          }
    }

and you can access this class function and property like

<?php echo Webapp\ControllerName::EMAIL; ?> 

and

<?php echo Webapp\ControllerName::myFunction(); ?>

Upvotes: 0

Related Questions