I developing a app and I want to get some data with CURL, I'm using Guzzle to get this informations. In every request I need to put the param api_token
. I don't have problems with requests but I need to create a globals variables or config this values. My ask is: how I can define this values and after use them in every request that I made?
$response = $client->request('POST', 'https://api.iugu.com/v1/payment_token?api_token=API_TOKEN', [
'json' => [
'account_id' => $account_id,
'method' => $method,
'test' => true,
'data' => [[
'number' => $number,
'verification_value' => $verification_value,
'first_name' => $first_name,
'last_name' => $last_name,
'month' => $month,
'year' => $year
]]
]
]);
When I create a project in pure PHP. I use this:
require 'environment.php';
$config = array();
if(ENVIRONMENT == 'development') {
define("BASE_URL", "http://localhost/plans/");
define("ACCOUNT_ID", "SECRET");
define("ACCESS_TOKEN", "SECRET");
$config['db_name'] = 'SECRET';
$config['host'] = 'localhost';
$config['db_user'] = 'root';
$config['db_password'] = 'XXXXXX';
} else {
define("BASE_URL", "http://www.blablabla/test");
define("ACCOUNT_ID", "SECRET");
define("ACCESS_TOKEN", "MY_TOKEN");
$config['db_name'] = 'INSERIR DATABASE';
$config['host'] = 'INSERIR HOST';
$config['db_user'] = 'INSERIR USUARIO';
$config['db_password'] = 'INSERIR SENHA';
}
global $database;
try {
$database = new PDO("mysql:dbname=".$config['db_name'].";host=".$config['host'], $config['db_user'],$config['db_password']);
} catch (Exception $ex) {
echo "Erro: ".$ex->getMessage();
exit;
}
And in the environment.php
:
<?php
define("ENVIRONMENT", "development");
//define("ENVIRONMENT", "production");
All these values should be in your .env
file. Then you need to read these values in a config file by using env()
helper:
'variable' => env('SOME_DATA'),
And then you'll be able to use these values globally with:
config('config_file.variable')
For Global Variables, you can create a file like constants.php
within config
folder.
Inside constants.php
file, you can define your global variable api_token
like below:
<?php
return [
'api_token' => env('API_TOKEN','https://api.iugu.com/v1/payment_token?api_token=API_TOKEN'),
];
?>
You can access this variable now using either of these two functions:
Config::get('constants.api_token')
config('constants.api_token')
For Blade file, do like below:
{{ config('constants.api_token') }}
Other alternative is to set Global Variable in __construct
function in Controller.php
file located at Controllers folder like below:
class Controller extends BaseController
{
public $api_token;
public function __construct(){
$this->api_token = "https://api.iugu.com/v1/payment_token?api_token=API_TOKEN";
}
I don't know exactly from your question that you want to make api_token
or ENVIRONMENT
as Global Variable but both solutions can resolve your issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With