Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a global constant available everywhere in the application?

Tags:

php

yii

How can I define an UPLOAD_DIR constant (or equivalent) so that I can use it everywhere?

I tried this as an application configuration parameter

'params'=>array(
            'upload_dir'=>Yii::app()->baseUrl . '/images/uploads/',
),

but Yii::app()->baseUrl cannott be used inside the config file.

like image 560
safiot Avatar asked Dec 12 '22 03:12

safiot


1 Answers

You can do this inside index.php, after the call to Yii::createApplication and before Yii::app()->run():

define ('UPLOAD_DIR', Yii::app()->baseUrl . '/images/uploads/');

You would then use it just like any other PHP constant, e.g. echo UPLOAD_DIR.

Edit: When I said after createApplication and before run, I meant exactly that (also, not that there is both a createWebApplication and a createApplication, which is a more generalized version of the former).

So if you currently have

Yii::createWebApplication(...)->run();

you have to split it into

Yii::createWebApplication(...);
define ('UPLOAD_DIR', Yii::app()->baseUrl . '/images/uploads/');
Yii::app()->run();

Another option would be to just add another property to your application class. For example, if you have a class MyApplication inside your protected/components directory then you can simply do this:

class MyApplication extends CWebApplication {
    // ...other code...
    public function getUploadDir() {
        return $this->baseUrl.'/images/uploads/';
    }
}

You would then access this as Yii::app()->uploadDir.

like image 85
Jon Avatar answered Jan 05 '23 00:01

Jon