I have a few constants that I'll need to define for my application, for example, SITE_KEY which would contain a random key for salt passwords.
I'm not sure where I should define those, though. I thought of placing them in public/index.php but that seems a bit messy. Is there a specific place where they should go, according to Zend or something?
Thanks
EDIT
I'm trying to do it this way:
In my application.ini I have this:
siteglobal.sitekey = "test"
and in my bootstrap.php file:
protected function _initGlobals()
{
$config = $this->getOptions();
define('SITE_KEY', $config['siteglobal']['sitekey']);
}
Still, this isn't working, when I try to echo SITE_KEY in my controller like this:
echo SITE_KEY;
It doesn't show anything. Any ideas?
In my application, I'm combining both Haim's and Yeroon's approaches. I'm storing application constants in my application.ini, then parsing them in the Bootstrap and putting them into Zend_Registry.
So, in the application.ini
constants.site_key = my_site_key
In the Bootstrap
protected function _initConstants()
{
$registry = Zend_Registry::getInstance();
$registry->constants = new Zend_Config( $this->getApplication()->getOption('constants') );
}
Then I can access these constants from any place in the application (model, controller, etc.)
Zend_Registry::getInstance()->constants->site_key
Have you tried Zend_Registry? It's used to store application-wide values, objects etc.
Store:
Zend_Registry::set('index', $value);
Retrieve:
$value = Zend_Registry::get('index');
in
application/configs/application.ini
myvar = myvalue
after get them like :
$myvar = $application->getOption('myvar');
read more ....
Related
I want to have one class that works with configuration settings. Configuration settings are stored inside config/ directory where I want them to be separated to files. When I call my
Config::gi()->getConfig('config_name')
I want the Config class to be able to access the file config/config_name.cfg.php and return the array (from that file) named exactly the same.
This is because I don't want to read all the configuration data if it's not needed. Also, I'm a bit afraid that setting up configuration inside $GLOBALS variable wouldn't be the best solution. I thought about requiring or including those files and then returning their content, but it also seems a bit unprofessional.
What is the best practice to read the configuration like this? Thank you in advance.
For example:
config/routes.cfg.php
$routes => [
'index' => new Route([
// route config here ...
])
];
and to get the routes array I would execute Config::gi()->getConfig('routes'); from helpers/Config.php class.
I'm not sure I would go this route, I would probably load all configs (most likely from a single file) into the class the first time and go from there. Also you can look at parse_ini_file() if you don't want to write out arrays when they change. But for your case, simply:
public function getConfig($name) {
if(file_exists("config/$name.cfg.php")) {
include("config/$name.cfg.php");
return ${$name}; //this translates to $routes in your example
}
return false;
}
Also, the next logical question might be how to save the config when it changes:
public function setConfig($name, $data) {
file_put_contents("config/$name.cfg.php", "$name = " . var_export($data, true) . ";");
}
$routes = array(/* with some stuff in it */);
Config::gi()->setConfig('routes', $routes);
I would like to create reusable code in controller in "Cakephp way". I would like to replace always one field in few controllers before render website. For example I would like to replace string in field "body". I can do this like this in show method:
public function show($id = null) {
$site = $this->Sites->findById($id)->first();
$new_value = 'test2';
$site['body'] = str_replace('test', $new_value, $site['body']);
}
Is there any better way to do this in cakephp way for example in initalize method or beforeRender? I can't use behavior here.
EDIT:
I know about components, but how to use it to replace all $site['body] (in my code) for all controller methods (so I would like to do this automatic, like behavior for entity)?
Read about Components.
Components are packages of logic that are shared between controllers. CakePHP comes with a fantastic set of core components you can use to aid in various common tasks. You can also create your own components. If you find yourself wanting to copy and paste things between controllers, you should consider creating your own component to contain the functionality. Creating components keeps controller code clean and allows you to reuse code between different controllers.
And see Component Callbacks.
You can use component
https://book.cakephp.org/3.0/en/controllers/components.html
Don't forget to load it in appController or where your need it
After edit :
#nexequ
Maybe if you set the beforeRender in your appController
public function beforeRender()
{
debug($this->request);
}
In $this->request->data array you have your data to replace.
Exemple:
data => array(
'Reunion' => array(
'begin' => '2017-01-13 20:00:00',
'end' => '2017-01-13 20:30:00'
)
If you find the way to get the model ("Reunion" in my example.)
You can do a trick like
replace --> $this->request->data[$model]['body']
I found solution with burzum help, I can use virtual property in src/Model/Entity:
protected function _getBody() {
$new_value = 'test2';
$test = str_replace('test2', $new_value, $this->_properties['body']);
return $test;
}
It will replace for instance 'test2' with $new_value in all controller methods.
I want to start using configuration.php file, like joomla or wp is using too to store some almost static variables like db logins, theme id or selected language. Problem is, that I dont know how to handle with updating this values. Is there possibility how to edit this variables separately, or I have to always replace whole content of the file? Lets say, that I have config.php file with content like:
class DB {
public $theme = 1;
public $db_host = 'abc';
public $db_user = 'adsabc';
public $db_pwd = 'dsads';
public $db_charset = 'utf8';
public $lang = 'gb';
public $debug= 0;
public $gzip = 0;
}
And I want to change variable $lang = 'gb'; to $lang = 'de'; What is most effective way to do this with php?
You can write a PHP script that will look for and replace those values, but parsing code with regex or similar would be a bad idea.
Instead, you'd be better to implement a JSON file or something similar which you could store your values in, e.g:
{
"lang": "gb",
// everything else
}
Then modify your configuration file to parse that file into variables:
private function parseConfig()
{
$json = json_decode(file_get_contents('yourconfig.json'));
$this->lang = $json->lang;
$this->anotherVar = $json->anotherVar;
}
This way, reading and writing variable data to a contained file is much more manageable than modifying a PHP file (introducing tenfold ways you can break your configuration file, which is the backbone of your site!).
You may have some success with var_export(). You'll probably need to eval() it to read it (make sure you do this inside of a function scope), then file_put_contents() the output of var_export. Then it will be editable by hand. It may or may not look exactly as you want it to, though.
for example, i have "config.php":
<?php
class Config {
public $var1 = 'ex1';
public $var2 = 'ex2';
}
?>
and i have "index.php"
<?php
include ('config.php');
$a = new Config();
$a->var1='changed_ex1';
$a->var2='changed_ex2';
UPDATE($a,'config.php');
?>
so here is the question - what shoud be in UPDATE function to write changes into config.php?=)
I highly do not recommend writing files to store configuration. I'd rather store config in the database if I need to change the settings during runtime.
But if you insist on your chosen path, your UPDATE function will need to read the entire file and either regex-replace the necessary keys, or simply re-render the entire thing based on stored data and the data you need to change.
Pretty often I need to access $config variables in views.
I know I can pass them from controller to load->view().
But it seems excessive to do it explicitly.
Is there some way or trick to access $config variable from CI views without
disturbing controllers with spare code?
$this->config->item() works fine.
For example, if the config file contains $config['foo'] = 'bar'; then $this->config->item('foo') == 'bar'
Also, the Common function config_item() works pretty much everywhere throughout the CodeIgniter instance. Controllers, models, views, libraries, helpers, hooks, whatever.
You can do something like that:
$ci = get_instance(); // CI_Loader instance
$ci->load->config('email');
echo $ci->config->item('name');
$this->config->item('config_var') did not work for my case.
I could only use the config_item('config_var'); to echo variables in the view
Your controller should collect all the information from databases, configs, etc. There are many good reasons to stick to this. One good reason is that this will allow you to change the source of that information quite easily and not have to make any changes to your views.
This is how I did it. In config.php
$config['HTML_TITLE'] = "SO TITLE test";
In applications/view/header.php (assuming html code)
<title><?=$this->config->item("HTML_TITLE");?> </title>
Whenever I need to access config variables I tend to use: $this->config->config['variable_name'];
echo $this->config->config['ur config file']
If your config file also come to picture you have to access like this for example I include an app.php in config folder I have a variable
$config['50001'] = "your message"
Now I want access in my controller or model .
Try following two cases one should work
case1:
$msg = $this->config->item('ur config file');
echo $msg['50001']; //out put: "your message";
case2:
$msg = $this->config->item('50001');
echo $msg; //out put: "your message"
$config['cricket'] = 'bat'; in config.php file
$this->config->item('cricket') use this in view
If you are trying to accessing config variable into controller than use
$this->config->item('{variable name which you define into config}');
If you are trying to accessing the config variable into outside the controller(helper/hooks) then use
$mms = get_instance();
$mms->config->item('{variable which you define into config}');
Example, if you have:
$config['base_url'] = 'www.example.com'
set in your config.php then
echo base_url();
This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).