How can I add parameter to config variable in codeigniter? - php

I am new to php and trying to add parameter to config variable. In my example, I am defining success/error messages in config file. I am able to access the config variable using:
$this->config->item('msg')
But I would like to add parameter in the message and pass it using:
$this->config->item
How can I do that?
Any help greatly appreciated.

$this->config->item() works fine.
For example if there's $config['foo'] = 'bar'; in the config using $this->config->item('foo') will be 'bar'

https://ellislab.com/codeigniter/user-guide/libraries/config.html
After dynamically setting my config variable in codeigniter how to access them from other controllers and models?
$this->config->set_item('item_name', 'item_value');
For example
$this->config->set_item('msg', 'Your Value goes here');
You can print this like this way
echo $this->config->item('msg');

Related

Laravel dynamic config settings

I'm using a package within my project and it stores a setting inside config/packagename
I would like to dynamically change this value inside the config file, this is how the file structure looks currently;
<?php
return [
'view_id' => '118754561',
'cache_lifetime_in_minutes' => 60 * 24,
];
I would like to change it to something like this -
'view_id' => Auth::user()->id,
Can you do this within the config file, or do you have to store some sort of variable to be updated later within a controller. Is there a way to place these variables in an env file and access these new variables from a controller?
This also is a generic solution to dynamically update your .env file (respective the individual key/value pairs)
Change the setting in your config/packagename like so:
return [
'view_id' => env('VIEW_ID', '118754561'),
etc...
]
Add an initial value into .env:
VIEW_ID=118754561
In an appropriate controller (e.g. AuthController), use the code below and call the function like this:
updateDotEnv('VIEW_ID', Auth::User()->id)
protected function updateDotEnv($key, $newValue, $delim='')
{
$path = base_path('.env');
// get old value from current env
$oldValue = env($key);
// was there any change?
if ($oldValue === $newValue) {
return;
}
// rewrite file content with changed data
if (file_exists($path)) {
// replace current value with new value
file_put_contents(
$path, str_replace(
$key.'='.$delim.$oldValue.$delim,
$key.'='.$delim.$newValue.$delim,
file_get_contents($path)
)
);
}
}
(The $delim parameter is needed if you want to make this function more generic in order to work with key=value pairs in .env where the value has to be enclosed in double quotes because they contain spaces).
Admittedly, this might not be a good solution if you have multiple users at the same time using this package in your project. So it depends on what you are using this package for.
NB: You need to make the function public of course if you plan to use it from other classes.
All configuration files of Laravel framework stored in the app/config directory.
so if we need to create custom configuration values it would be better to keep separate our custom configuration in custom file.
so we need to create custom file in app/config directory.
Laravel auto read this file as a config file and will auto manage it
In this topic we are working with custom configuration in laravel and get configuration value in controller or view.
Now i am going to explain how to create a custom config file in Laravel so that we can implement dynamic feature over to this.
create a file in app/config/custom.php which have config keys and value like:-
return array(
'my_val' => 'mysinglelue',
'my_arr_val' => array('1', '2', '3'),
);
Now need to get these config values in view/controller so we will use Config class get() method for this
Syntax:
echo Config::get('filename.arraykey');
where filename is the config file’s name, custom in our case, and key is the array key of the value you’re wanting to access.
In Our case it will be as:
echo Config::get('custom.my_val');
Create run time configuration in laravel :-
Configuration values which are set at run-time are will set for the current request, not be carried over to subsequent requests.
You can pass the dynamic values over here so that you can modify the config file dynamically over here using the isset() functions.
Like how the #Kundan roy as suggested using of the isset() the same condition applies here to. But this one is the alternative method that will work for the dynamic setting of the values in the config.
Config::set('custom.my_val', 'mysinglelue');
Hence by using this method you can create the dynamic config files based on the values that you need.
Since Laravel v5.2 you can dynamically set config values this way:
<?php
config(['app.timezone' => 'America/Chicago']);
$value = config('app.timezone');
echo $value;
// output: 'America/Chicago'
If you want to actually edit the config files (either config/packagename.php or .env) then you may follow matthiku's answer.
However, if I were you, I guess I'd rather want to configure this 3rd party package based on some value defined at runtime, instead of modifying any file (which by the way won't take effect until the next request, when the env values are read again).
So, in my opinion the cleanest way to do this is:
store your desired value in the config data:
config(['packagename.view_id' => Auth::user()->id]);
However, you may notice this probably won't work: the service provider which provides the service you need is often registered before the request is processed, that is, before your config change takes place. So you are still getting the service with old values config.
So, how could you have the service provider be called only when needed and not before (that is, after setting the new config value)? You could make it a deferred provider. Following your example of "spatie laravel-analytics", replace in config/app.php this line:
Spatie\Analytics\AnalyticsServiceProvider::class
with this one:
App\Providers\AnalyticsDeferredServiceProvider::class
and finally create the App\Providers\AnalyticsDeferredServiceProvider class, with:
:
<?php
namespace App\Providers;
use Spatie\Analytics\Analytics;
use Spatie\Analytics\AnalyticsServiceProvider;
class AnalyticsDeferredServiceProvider extends AnalyticsServiceProvider
{
protected $defer = true;
public function provides()
{
return [Analytics::class];
}
}
This way you can have the provider read the config values when you are about to instantiate the service, after you set any runtime config values.
Use this in controller when you need to change.
<?php
use Illuminate\Support\Facades\Config;
//[...]
$user_id = Auth::user()->id;
Config::set('view_id', $user_id );
You can do like this.
In your custom config file. Add the following code You can send your id dynamically from the query string.
'view_id' => isset($_REQUEST['view_id'])?$_REQUEST['view_id']:null,
To get view id
echo config('app.view_id'); // app is config file name
config(['packagename.view_id' => Auth::user()->id]);
Actually if you are that point of code which forces you to make the config values dynamic, then there should be something wrong with your code flow, as the use of config file is just for initializing required values - which should be defined before the app is loaded.
Making config values dynamic is a "BAD PRACTICE" in the world of coding.
So there is the following alternative for your problem.
Define value in .env file (optional)
VIEW_ID=your_view_id_here
Use value inside Controller
$auth_id = auth()->user()->id;
$view_id = env('VIEW_ID', $auth_id);
// If .env file doesn't contains 'VIEW_ID' it will take $auth_user as the view_id
Hope this helps you!
config::set() doesn't works for me in laravel 8. but I got best answer for Create or edit Config file
config(['YOUR-CONFIG.YOUR_KEY' => 'NEW_VALUE']);
$text = '<?php return ' . var_export(config('YOUR-CONFIG'), true) . ';';
file_put_contents(config_path('YOUR-CONFIG.php'), $text);
just try this way this works for me.
original answer you can see here

How to access custom config variable in codeigniter controller

I have a codigniter project with a custom config file called
application/config/my_config_variables.php:
This contains
<?php
$config['days'] = 20;
in :
application/config/autoload.php
I've added:
$autoload['config'] = array('my_config_variables');
when I try to access this in my controller using:
echo $this->$config['new_daily_contacts'];
I get:
Fatal error: Cannot access empty property.
What am I doing wrong?
addendum:
In my controller I've added:
// An alternate way to specify the same item:
$my_config = $this->config->item('my_config_variables',true);
var_dump($my_config);
this outputs FALSE -- why?
Look at the config documentation on Codeigniter.
echo $this->config->item('new_daily_contacts');
That will try to grab $config['new_daily_contacts'] but from your post it looks like you only have $config['days'] in your config file. But this should get you pointed in the right direction.
Alternate Way
With the alternate way you're trying to load the config, but you're using the item method, not the load method. On the item method, the 2nd parameter is the index you want to reference in the config array. For instance. With your example above.
$my_config = $this->config->load('my_config_variables', true);
var_dump($my_config);
$days = $this->config->item('days', 'my_config_variables');
Because passing true as the 2nd parameter on the load method will create an index with the same name as the config file. This helps avoid any conflicts if there happen to be other config files that contain the same config name.
$config['days']; becomes $config['my_config_variables']['days']
In order to access that config variable you have to pass the index in the item method.
https://github.com/bcit-ci/CodeIgniter/blob/2.1-stable/system/core/Config.php#L189

codeigniter global variable need to be accessed by multiple controllers

I am new to codeigniter , In my program i want a variable need to be accessed by multiple controllers,
It's not a constant variable, value of variable changes ,
Sorry , My mistake
I want to store a JSON object to be precise
Pls help me to figure this out.
Thanks in advance.
You can create a base controller with an attribute for your variable, then have your controllers extend that base controller.
Option 1
Since you are using CodeIgniter and sessions then something like this could work out for you:
set it
$someJSONobject = 'JSON';
$this->session->set_userdata('GLOBAL_JSON', $someJSONobject);
retrieve it
$someJSONobject = $this->session->userdata('GLOBAL_JSON');
echo $someJSONobject->subitem;
Make sure you are storing sessions in a DB if you go with this option because Cookie space is VERY limited
Option 2
Even if you are not using CodeIgniters' session implementation then you can do something quite similar in native PHP:
$someJSONobject = 'JSON';
$_SESSION['GLOBAL_JSON'] = $someJSONobject;
Appending on Rooneyl's solution you may want to save that value on session which is easier to access from all end
Session docs

CodeIgniter - accessing $config variable in view

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).

How do you create variables in actions.class.php so that they are accessible in layout.php?

In Symfony 1.2, how do you create variables in actions.class.php so that they are accessible in layout.php?
This page has some information about it: http://trac.symfony-project.org/wiki/Symfony11LayoutUpgrade
It seems you can get the desired effect using this following code:
$this->getResponse()->setSlot('title', 'insert your title here');
And then use this in the layout file:
<title><?php echo get_slot('title') ?></title>
I think, by default, you can't, since it should be against the MVC pattern.
You should better pass variable to your view, but without using global (or kind of).

Categories