My library class contains a constant with a string value.
I want to set its value from the config item defined in the codeigniter config file.
You can do this in config/config.php AND config/constants.php.
you just need to write below kind of thing
i.e
define('PAY_AMOUNT', '$120');
The value is defined at the config file and its value different in testing and production environment. Its a third party account key and its value change between the environment.
Eg:
$config['my_key'] = 'skdflksd1654612'; // for testing
$config['my_key'] = 'poikjij788miomk'; // for production
I have a library in which a constant value need to set from this config item. That's my requirement.
Class Mylibrary{
const MYKEY = 'skdflksd1654612'; // for testing
const MYKEY = 'poikjij788miomk'; // for production
function __construct()
{
}
}
Related
I'm trying to access variable from markup (Twig) in octoberCMS code module. This variable is printed in loop by plugin builder.
I have this variable in markup:
{% set frontId = record.id %}
{{frontId}}
And I want to access {{frontId}} variable it in code module.
function onStart()
{
$this["slots"] = Db::table('oblikovanje_izobrazevanja_vnos')->where('id', $frontId)->value('free_slots');
echo $frontId;
}
Hmm, unfortunately you can not pass variables from Markup to Code section. Because Code section as whole executed before Markup so you can not do that.
It seems you are using Builder's Record details component so you must be passing :id from url
Solution 1 [ use param ]
function onStart() { // you can use onEnd as well
$frontId = $this->param('id'); // this will get :id param from url
// now slots variable are available in `Markup section`
$this["slots"] = Db::table('oblikovanje_izobrazevanja_vnos')->where('id', $frontId)->value('free_slots');
}
Solution 2 [ you can use global component array with its alias name, make sure to use onEnd life-cycle hook ]
function onEnd () { // you must use onEnd as at this moment all components are initialized properly
// we can access component from $this->components with alias name and get its details
$frontId = $this->components['builderDetails']->record->id;
// now slots variable are available in `Markup section`
$this["slots"] = Db::table('oblikovanje_izobrazevanja_vnos')->where('id', $frontId)->value('free_slots');
}
Reference Screenshot
if any doubts please comment.
I want to assign a default value in Laravel model but the value should come from the config file.
I am writing below code but its giving me error
protected $attributes = [
'is_generation' => true,
'price' => config('test.MY_PRICE'),
];
it's showing me an error like Constant expression contains invalid operations
How can I get value from config file and set in $attribute variable in Laravel model file?
You can use the saving model event by adding this code to your Eloquent Model:
protected static function boot()
{
// sets default values on saving
static::saving(function ($model) {
$model->price = $model->price ?? config('test.MY_PRICE');
});
parent::boot();
}
With this code in place, if the field price is null, it will have assigned a value from the config key just a moment before saving the Model in the database.
BTW you can change the check like if it's an empty string or less then a number and so on, this is only an example.
Class member variables are called "properties". You may also see them
referred to using other terms such as "attributes" or "fields", but
for the purposes of this reference we will use "properties". They are
defined by using one of the keywords public, protected, or private,
followed by a normal variable declaration. This declaration may
include an initialization, but this initialization must be a constant
value--that is, it must be able to be evaluated at compile time and
must not depend on run-time information in order to be evaluated.
The only way you can make this work is :-
<?php
namespace App;
class Amazon
{
protected $serviceURL;
public function __construct()
{
$this->serviceURL = config('api.amazon.service_url');
}
}
You can use attribute mutator as explained here: https://laravel.com/docs/5.8/eloquent-mutators#defining-a-mutator
Class Example{
public function setPriceAttribute(){
return $this->attributes['price'] = config('test.MY_PRICE');
}
}
I'm creating a model that I will use to authenticate users for API access, and I have a secret field where I want to store a Base64 encoded uuid/v4 generated value.
I went through the different field types and options, but still not seeing how I could achieve this.
Is there a way to hook in model instance creation, and set the value of my secret field ?
Yes, you can use the pre hooks.
In your situation, the basics would be:
AuthenticationModel.schema.pre("save", function(next) {
const secretValue = generateSecretValue();
this.secret = secretValue;
next();
});
That would go before your final AuthenticationModel.register(); in your model.js file.
This is how I set it up, also with the pre-save hook. My problem before was that I was getting the same random number again until I restarted the server.
Store.schema.pre('save', function (next) {
if (!this.updateId && this.isNew) {
// generates a random ID when the item is created
this.updateId = Math.random().toString(36).slice(-8);
}
next();
});
Using this.isNew was also useful in my case.
Writing tests for an existing API, there are many cases where the database has been modified. What I have been doing is something as follows:
public function testPut()
{
//setup
/*Copy an existing record and take its data as an array.
* the function being tested will take an array of data
* and create a new record. Using existing data guarantees
* the data is valid.
*/
$customerObj = Customer::getInstance(); //regular instantiation disabled in this api
$cust = ArCust::first()->toArray();
$oldNum = $cust['CUST_NO'];
unset($cust['CUST_NO']);
$custNo = rand(1, 9999999999999);
//test
/*put() creates a new customer record in the database
and returns the object.
*/
$this->assertInternalType('object', $customerObj->put($custNo, $cust));
//cleanup
/*manually remove the newly created record.
*/
ArCust::whereNam($cust['NAM'])->whereNotIn('CUST_NO', [$oldNum])->delete();
}
I am now running into instances where the API creates or updates many tables based on foreign keys. It would take far too much time to go through and manually reset each table.
The DatabaseTransaction trait provided by Laravel is supposed to take care of resetting everything for you. However, when I use it, I still find the test-created records in the database.
Here is how I have used it:
class CustomerTest extends TestCase
{
use DatabaseTransactions;
public function testPut()
{
//setup
$customerObj = Customer::getInstance();
$cust = ArCust::first()->toArray();
$oldNum = $cust['CUST_NO'];
unset($cust['CUST_NO']);
$custNo = rand(1, 9999999999999);
//test
$this->assertInternalType('object', $customerObj->put($custNo, $cust));
}
}
Am I using this incorrectly? Getting DatabaseTransactions to work correctly will save an incredible amount of time, as well as make the testes more readable to other people.
The issue was that we had multiple database connections defined in config > database.
In the database.php conf file, I changed the default connection to the correct database using its name as defined in the setup:
$connection = 'counterpoint';
and DatabaseTransactions now works.
This next step to this solution is to direct the connection of each test to the appropriate database rather than change the global connection.
I want to generate global variables in CodeIgniter by creating my own library and config file. This is what I wrote ini my library file, let's say globalvars.php. I put it in /application/libraries.
class Globalvars{
function __construct($config = array())
{
foreach ($config as $key => $value) {
$data[$key] = $value;
}
$CI =& get_instance();
$CI->load->library('session');
$CI->load->vars($data);
}
}
I want the user id stored in the session to be available in global variable, so I wrote this in my config file. It's named also globalvars.php. It's in /application/config directory.
$config['user']=$this->session->userdata('id');
I then test to see if it's working by write it in my controller this way.
echo $data['user'];
But I get this error in the browser
Message: Undefined property: CI_Loader::$session
Filename: config/globalvars.php
It seems that the session functions is not defined yet. How can I get it work? What have I missed here? Any help would be appreciated.
You cannot use the session library in config file.
The config files are loaded before any libraries, so $this->session is undefined.
The config.php has to be loaded in order for the Session class to even be initialized, as it reads settings from that file.
A lot of issues with this type of thing (setting some "global" data) can be resolved using a base controller, and extending it in your controllers.
// core/MY_Controller.php
MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct(); // Now the Session class should be loaded
// set config items here
}
}
"Normal" controllers will now extend MY_Controller to take advantage of this.
See: http://codeigniter.com/user_guide/general/core_classes.html for more details.
In addition, when you load->vars(), they are available to the view layer only, it does not create a global variable called $data as you seem to be trying to access. If you do this:
$this->load->vars(array('user' => '1'));
You would access it in a file loaded by $this->load->view() like this:
echo $user; // outputs "1"
See: http://codeigniter.com/user_guide/libraries/loader.html
$this->load->vars($array)
This function takes an associative array as input and generates
variables using the PHP extract function. This function produces the
same result as using the second parameter of the $this->load->view()
function above. The reason you might want to use this function
independently is if you would like to set some global variables in the
constructor of your controller and have them become available in any
view file loaded from any function. You can have multiple calls to
this function. The data get cached and merged into one array for
conversion to variables.
I will say that as an experienced Codeigniter user, the concept of a "global vars" class is a bit wonky and probably unnecessary, especially when it's already so easy to get and set config items. You could definitely run into some confusing issues and variable name conflicts with this method (pre-loading lots of view variables on every request).