Including Classes without having to redefine - php

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.

Related

Dynamic Database Switch - Codeigniter

I want to switch my codeigniter multiple database on runtime. My Default database will run thoroughly the page but when I needed to switch to other database based on scenario or requirement then I can do. The common model function will work for the all different databases. So, I want to use same model and same function for multiple database connection using dynamic selector without using session or without passing function variable
To achieve this I set a name in cofig and when I call my model I set the required database name in controller before calling model and then I tried to get the name in model which is set in controller. But unfortunately I'm not getting the name from controller to model.
Database Configuration File -
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'pass'
'database' => 'db1'
.......
);
$db['anotherDB'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'pass'
'database' => 'db2'
.......
);
Controller -
$this->config->set_item('active_db', 'anotherDB');
$sql = 'select * from user';
$anotherDB_record = $this->model->customQuery($sql);
print_r($anotherDB_record);
$this->config->set_item('active_db', 'default');
$sql = 'select * from customer';
$default_record = $this->model->customQuery($sql);
print_r($default_record);
Mode -
protected $database;
function __construct() {
parent::__construct();
$oDB = $this->config->item('active_db');
$this->database = $this->load->database($oDB, TRUE);
}
function customQuery($sql){
$query = $this->database->query( $sql );
return $query->result();
}
This is the way I have tried to switch my database. If you guys have any other best solution to switch multiple database then please feel free to suggest me.
Try bellow example for dynamically configure another database
common model
function getOtherDB($groupID) {
$getRecord = $this->common_model->getRow('group_master', 'GroupID', $groupID);
if ($getRecord) {
$config['database'] = $getRecord->DBName;
$config['hostname'] = $getRecord->DBHostIP;
$config['username'] = $getRecord->DBHostUName;
$config['password'] = $getRecord->DBHostPassw;
$config['dbdriver'] = "mysqli";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;
$DB2 = $this->load->database($config, TRUE);
if ($DB2) {
return $DB2;
}
}
return FALSE;
}
In the above example, I have group_master table which has group wise database details by passing GroupId I fetch the record and set Another database according to group Make sure your all database configuration information stored in the database is encrypted format Use below example to fire query on Other database
$result = $DB2->query("select * from group");
// $DB2 is other database instance you can create multiple db connection using above methos

How to set global variables in Laravel?

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.

Variable of object set in construct is out of scope in destruct

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

How to get a bootstrap resource in a controller plugin in Zend Framework

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();

zend_db and join

I am trying to understand how to use Zend_DB in my program but I have some problems. The class below (DatabaseService) works when I pass it a simple query. However, if I pass it a query with a join clause my page just hangs and no error is returned. I cut and paste the qry in a query browser and it is valid
Any help would be great
$SQL = "select name from mytable"
$db = new DatabaseService($dbinfo)
$db ->fetchall($SQL ) // works
-----------------------------------------------------------
$SQL = "select count(*) as cnt from EndPoints join CallID on EndPoints.`CallID` = CallID.CallID where EndPoints.LastRegister >= '2010-04-21 00:00:01' and EndPoints.LastRegister <= '2010-04-21 23:59:59' "
$db = new DatabaseService($dbinfo)
$db ->fetchall($SQL ) // DOES NO WORK
class DatabaseService
{
function DatabaseService($dbinfo,$dbname="")
{
try
{
$dbConfig = array(
'host' => $this->host,
'username' => $this->username,
'password' => $password,
'dbname' => $this->dbname );
$this->db = Zend_Db::factory($this->adapter, $dbConfig);
Zend_Db_Table::setDefaultAdapter($this->db);
}
catch(Zend_Exception $e)
{
$this->error = $e->getMessage();
Helper::log($this->error);
return false;
}
}
public function connnect()
{
if($this->db !=null)
{
try
{
$this->db->getConnection();
return true;
}
catch (Zend_Exception $e)
{
$err = "FAILED ::".$e->getMessage()." <br />";
}
}
return false;
}
public function fetchall($sql)
{
$res= $this->db->fetchAll($sql);
return $res;
}
}
I can't see why that wouldn't work. It could be a bug in a particular release of ZF but as far as I can tell there are no SQL syntax errors. What you could do is Bootstrap the Zend_Db class somewhere in your system like in the index.php file just as you were doing in your DatabaseService class:
$dbConfig = array(
'host' => 'hostname',
'username' => 'username',
'password' => 'password',
'dbname' => 'dbname'
);
$db = Zend_Db::factory('mysqli', $dbConfig);
$db->setFetchMode(Zend_Db::FETCH_OBJ);
Zend_Db_Table::setDefaultAdapter($db);
And then Zend Framework should handle the connection process for you. Then instead of having a DatabaseService class you just create a model for each table you need like so:
<?php
class EndPoints extends Zend_Db_Table_Abstract
{
protected $_name = 'EndPoints';
/**
* the default is 'id'. So if your table's primary key field name is 'id' you
* will not be required to set this. If your primary key is something like
* 'EndPointsID' you MUST set this.
* #var primary key field name
*/
protected $_primary = 'EndPointsID';
}
Doing this will automagically give you access to functions such as fetchRow(), fetchAll(), find(), etc. Then you can also use Zend_Db_Table_Select for your queries which can be quite useful. Like so:
<?php
$endPointsModel = new EndPoints();
$callIdCount = $endPointsModel->getCallIdCount('2010-04-21 00:00:01', '2010-04-21 00:00:01');
Then in your EndPoints model you would create that function like so:
...
public function getCallIdCount($fromDate, $toDate)
{
$cols = array('cnt' => 'count(*)');
$select = $this->select->setIntegrityCheck(false) // this is crucial
->from($this->_name, $cols)
->join('CallID', "{$this->_name}.CallID = CallID.CallID", array())
->where("{$this->_name}.LastRegister >= ?", $fromDate)
->where("{$this->_name}.LastRegister <= ?", $toDate);
// if you need to see what the whole query will look like you can do this:
// echo $select->__toString();
return $this->fetchAll($select);
{

Categories