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.
Related
I have this code in layout/main.php:
$userId = Yii::$app->user->id;
$data = User::find()->where('id ="'.$userId.'"')->one();
$type = $data['type'];
Yii::$app->view->params['Type'] = $type;
I cant' access $this->params['Type'] from any controller except SiteController. If I navigated using any another controller i got this error:
PHP Notice – yii\base\ErrorException
Undefined index: Type
If I duplicated my query in every controller, It works well. But I don't want to do that. How to make it globally at the backend only?
You can definitely accomplish this (without explicitly session coding) successfully by
In your model (User.php)
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
// return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
$User = static::findOne(['id'=>$id]);
if(!$User)
{
return null;
}
else
{
$dbUser =
[
'id' => $User->id,
'image'=>$User->image,
'type'=>$User->type,
// 'usertype'=>$User->user_type, set other attributes too
'username' => $User->username,
'first_name' => $User->first_name,
'last_name' => $User->last_name,
'email' => $User->email,
];
return new static($dbUser);
}
}
Now if the user has logged in successfully, then you use all this attributes globally (through out the project For eg in model, view controller) by
For eg
echo Yii::$app->user->identity->id;
echo Yii::$app->user->identity->image;
echo Yii::$app->user->identity->type;
echo Yii::$app->user->identity->username;
echo Yii::$app->user->identity->frst_name;
echo Yii::$app->user->identity->last_name;
echo Yii::$app->user->identity->email;
What about using session :
$session = new \yii\web\Session;
$session->open();
$value1 = $session['name1']; // get session variable 'name1'
$value2 = $session['name2']; // get session variable 'name2'
foreach ($session as $name => $value) // traverse all session variables
$session['name3'] = $value3; // set session variable 'name3'
See docs for more details.
So, I started writing a bootstrap script for a micro framework I'm working on for learning purposes (both learn more about programming, php and oop) and I came across this weird unexpected behavior.
The variable $config which starts a new object of Config() class is being called in Bootstrap's __construct which is public, then it is being used in Bootstrap's __destruct which is also public. The variable itself of $config is public and declared before __construct as you can see below.
Now, what's weird is that I get a notice and fatal error from using $config in __destruct, it says the variable doesn't exist and the fatal error is calling a member function on a non object (because $config doesn't exist)
Here is the script, hope someone could point out why this weird behavior happens, it is possible that I'm missing something and the behavior makes sense but well, I'm missing it then please point it out.
<?php
basename($_SERVER["PHP_SELF"]) == "bootstrap.php" ? die("No direct script access allowed") : '';
class Bootstrap
{
public $config;
protected $start_route;
public function __construct()
{
$this->settings();
$config = new Config();
$this->database();
$this->routing();
$start_route = new Route($config);
$start_route->initiate();
}
public function run()
{
$db_info = new DatabaseInfo();
$database = new Database([
'database_type' => $db_info->get_db('dbdriver'),
'database_name' => $db_info->get_db('database'),
'server' => $db_info->get_db('hostname'),
'username' => $db_info->get_db('username'),
'password' => $db_info->get_db('password'),
'charset' => $db_info->get_db('dbcharset'),
'port' => $db_info->get_db('port'),
'prefix' => $db_info->get_db('dbprefix'),
// driver_option for connection, read more from
// http://www.php.net/manual/en/pdo.setattribute.php
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL
]
]);
/*
*
* Read is much faster than Write,
* while INSERT will increase load time by ~40ms per each query,
* COUNT will only increase by ~2ms
*
*/
$count = $database->count('site_log', [
'log_type' => 1
]);
/*
$database->insert('site_log', [
'remote_addr' => '127.0.0.1',
'request_uri' => '/',
'log_type' => 1,
'message' => 'Test Query'
]);
*/
echo 'The are ' . $count . ' rows in log with severity level of 1!<br />';
}
// Since it's being called from __constrcut, it will run before run()
private function settings()
{
require BOOTPATH.'core\\config'.CLASSFIX.EXT;
}
// Since it's being called from __constrcut, it will run before run()
private function database()
{
require BOOTPATH.'core\\database'.CLASSFIX.EXT;
return;
}
// Since it's being called from __constrcut, it will run before run()
private function routing()
{
require BOOTPATH.'core\\router'.CLASSFIX.EXT;
return;
}
// Since it's being outputed within __destrcut, it will run after run() and basically last
public function __destruct()
{
$script_end = (float) array_sum( explode( ' ',microtime() ) );
echo 'Welcome to ' . $config->get_conf('site_name') . '<br />';
echo 'Processing time: '. sprintf( '%.4f', ( $script_end - APP_START ) ).' seconds';
}
}
When you do this:
$config = new Config();
you are creating a new $config object in the scope of the constructor, you are not populating the $config property of the Bootstrap class
You have to use $this->config; to access the class property
So I know that in order for a.class.php to be used within b.class.php I would need to have the a class included in the b class file. My question is this.
I have two classes files at the moment within my website platform. db.class.php and account.class.php
db.class.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => SITEHOST,
'database' => SITEDB,
'username' => SITEUSER,
'password' => SITEPASS,
);
public $realmdb = '';
public $realmconfig;
public $realmsettings = array(
'host' => REALMHOST,
'database' => REALMDB,
'username' => REALMUSER,
'password' => REALMPASS,
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->realmdb = new PDO(
"mysql:host={$this->realmsettings['host']};" .
"dbname={$this->realmsettings['database']};" .
"charset=utf8",
"{$this->realmsettings['username']}",
"{$this->realmsettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->realmdb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
account.class.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/settings.php');
class account extends db {
public function Login() {
$query = <<<SQL
SELECT id
FROM profile
WHERE password = :password
SQL;
$resource = $db->sitedb->prepare ( $query );
$resource->execute( array(
':password' => sha1(strtoupper($_POST['email'].':'.$_POST['password'],
));
$row_count = $resource->rowCount();
echo $row_count;
}
}
$account = new account();
This current format tells me that db cannot be redefined, however if I remove the requirement of including the settings file which has
foreach (glob("functions.d/*.class.php") as $class)
{
include $class;
}
It then tells me that class db cannot be found. What way can I work around to have this work correctly?
Turns out the best way to accomplish this was to keep the includes correctly and have all classes within the same file and within my include page utilizing classes have global $db or global $account depending on what I class function I was calling on.
in my Zend Framework project, I use a Service Layer, however I don't really know where to handle errors.
For example, let's say I've a UserService::updateUser($data);
What if I've:
$data = array(
'userId' => 2,
'firstName' => 'Jane',
'lastName' => 'Doe',
);
And user with id 2 doesn't exist?
Where and how would you handle such errors?
You can forward to a specific controller to handle all your business errors, like this :
if ($error=true)
return $this->_forward('standarderror', 'businesserror', 'default',
array('msgtitle' => $this->view->translate('item_not_found'),
'msg' => $this->view->translate('item_not_found_msg')));
and where your BusinesserrorController looks like :
class BusinesserrorController extends Zend_Controller_Action {
public function init() {
$this->_helper->viewRenderer->setNoRender();
}
public function standarderrorAction() {
$msgtitle = $this->_getParam('msgtitle');
$msg = $this->_getParam('msg');
$this->view->errortitle = $msgtitle;
$this->view->errormessage = $msg;
$this->view->nextstep = $this->view->translate('return_to_the_homepage');
$this->view->nextstepurl = "/";
echo $this->render('error/businesserror', null, true);
}
}
you can parametrize the forwarded url as well ;)
protected function _initDatabase()
{
$params = array(
'host' => '',
'username' => '',
'password' => '',
'dbname' => '',
);
$database = Zend_Db::factory('PDO_MYSQL', $params);
$database->getConnection();
return $database;
}
.
class App_Controller_Plugin_Test extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Http $request)
{
// how i get database?
}
}
You can always get a reference to the front controller:
$front = Zend_Controller_Front::getInstance();
From that you can get the bootstrap:
$bootstrap = $front->getParam("bootstrap");
From the bootstrap you can get bootstrap plugins:
if ($bootstrap->hasPluginResource("database")) {
$dbResource = $bootstrap->getPluginResource("database");
}
$db = $dbResource->getDatabase();
But that's a lot of extra plumbing!
Honestly, you'd be better off storing the database adapter object in the registry during your bootstrap:
protected function _initDatabase()
{
$params = array(
'host' => '',
'username' => '',
'password' => '',
'dbname' => '',
);
$database = Zend_Db::factory('PDO_MYSQL', $params);
$database->getConnection();
Zend_Registry::set("database", $database);
return $database;
}
Then you can get the database adapter anywhere:
Zend_Registry::get("database");
See also my answer to What is the “right” Way to Provide a Zend Application With a Database Handler
Too bad there's nothing like Zend_Controller_Action's getInvokeArg("bootstrap") in a plugin. You could always get the bootstrap reference through the front controller:
$db = Zend_Controller_Front::getInstance()->getParam("bootstrap")->getResource("database");
But what I usually do is
Zend_Registry::set('database', $database);
and then in your plugin:
try
{
$db = Zend_Registry::get('database');
}
catch (Zend_Exception $e)
{
// do stuff
}
Easier, and database can be retrieved pretty much anywhere in the application.
[I need to check this against some working code on another machine. I believe it's something like this...]
$db = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('db');
$db = Zend_Db_Table::getDefaultAdapter();