Codeigniter autoloader isn't picking up cassandra library - php

Hi I am new to cassandra database. I am downloaded phpcassa from
https://github.com/mauritsl/php-cassandra.
When I tried to autoload cassandra library from application/config/autoload.php I got non existence class cassandra error.
Please help me to solve this issue.

o Place all Cassandra related files into application/library/ folder.
Remove the name space from each Cassandra class file.
"namespace Cassandra;"
Your file name and class name should match to load the library in auto load function in codeigniter.
Cassandra file class name is "Connection".
Change the class name as "Cassandra"
Your constructor expects a parameter to connect the database. You can't pass parameters while loading autoload library.
Change your constructor method name as connect
Using $this->cassandra->connect($host,$keyspace,$options) you can process the connection.
Rename the __construct into connect
/**
* Connect to Cassandra cluster.
*
* #param mixed $host
* Hostname as string or array of hostnames.
* #param string $keyspace
* #param array $options
*/
public function connect($host, $keyspace = NULL, $options = array()) {
$this->options += $options;
if (empty($host)) {
throw new InvalidArgumentException('Invalid host');
}
if (!is_array($host)) {
$host = array($host);
}
shuffle($host);
while ($host) {
$hostname = array_pop($host);
try {
$this->transport = new Transport($hostname, $this->options['connect_timeout'], $this->options['stream_timeout']);
break;
}
catch (Exception $e) {
if (empty($host)) {
// No other hosts available, rethrow exception.
throw $e;
}
}
}

Related

MongoDb error with php 7 on xampp CodeIgniter

I am getting the following error when running the app in xampp with Php 7. I am new to mongoDb. Can't figure out what might solve this issue. Any help or suggestion about the problem will be highly appreciated. Thank you for your help. Below is the code I believe have some issue.
Error:
An uncaught Exception was encountered
Type: Error
Message: Class 'MongoClient' not found
Filename: C:\xampp\htdocs\Web\application\libraries\Mongo_db.php
Line Number: 49
Backtrace:
File: C:\xampp\htdocs\Web\application\controllers\Home.php Line: 7
Function: __construct
File: C:\xampp\htdocs\Web\index.php Line: 315 Function: require_once
libraries\Mongo_db.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mongo_db
{
private $debug;
private $write_concerns;
private $journal;
private $selects = array();
private $updates = array();
private $wheres = array();
private $limit = 999999;
private $offset = 0;
private $sorts = array();
private $return_as = 'array';
public $benchmark = array();
public function __construct()
{
//Check mongodb is installed in your server otherwise display an error
/*if ( ! class_exists('Mongo') && ! class_exists('MongoClient'))
{
show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}*/
if (!class_exists('MongoDB\Driver\Manager')) {
show_error("The MongoDB PECL extension has not been installed or enabled", 500);
}
//get instance of CI class
if (function_exists('get_instance'))
{
$this->_ci = get_instance();
}
else
{
$this->_ci = NULL;
}
//load the config file which we have created in 'config' directory
$this->_ci->load->config('mongodb');
$config='default';
// Fetch Mongo server and database configuration from config file which we have created in 'config' directory
$config_data = $this->_ci->config->item($config);
try{
//connect to the mongodb server
$this->mb = new MongoClient('mongodb://'.$config_data['mongo_hostbase']);
//select the mongodb database
$this->db=$this->mb->selectDB($config_data['mongo_database']);
}
catch (MongoConnectionException $exception)
{
//if mongodb is not connect, then display the error
show_error('Unable to connect to Database', 500);
}
}
/**
* --------------------------------------------------------------------------------
* Aggregation Operation
* --------------------------------------------------------------------------------
*
* Perform aggregation on mongodb collection
*
* #usage : $this->mongo_db->aggregate('foo', $ops = array());
*/
public function aggregate($collection, $operation)
{
if (empty($collection))
{
show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500);
}
if (empty($operation) && !is_array($operation))
{
show_error("Operation must be an array to perform aggregate.", 500);
}
try
{
$documents = $this->db->{$collection}->aggregate($operation);
//$this->_clear();
if ($this->return_as == 'object')
{
return (object)$documents;
}
else
{
return $documents;
}
}
catch (MongoResultException $e)
{
if(isset($this->debug) == TRUE && $this->debug == TRUE)
{
show_error("Aggregation operation failed: {$e->getMessage()}", 500);
}
else
{
show_error("Aggregation operation failed: {$e->getMessage()}", 500);
}
}
}
}
?>
config/mongodb.php
<?php
//mongodb host
$config['default']['mongo_hostbase'] = 'localhost';
//mongodb name
$config['default']['mongo_database'] = 'appname';
//mongodb username - by default, it is empty
$config['default']['mongo_username'] = 'root';
//mongodb password - by default, it is empty
$config['default']['mongo_password'] = 'root';
?>
config/mongo.php
<?php
$config['mongo_server'] = 'localhost:27017';
$config['mongo_dbname'] = 'appname';
?>
The MongoCLient class was provided by pecl install mongo. But pecl/mongo is not available for php7 and deprecated in favor of pecl/mongodb. But with pecl/mongodb you'll need to use MongoDB\Driver\Manager instead of MongoClient
Please see here for further reading.
Once you install MongoDB you cannot connect with PHP directly. You need to install the MongoDB Driver for PHP which you can find in the following URL
http://php.net/manual/en/mongodb.installation.php
Based on the type of the OS you can download the one.
Once your done with that. You can use the composer to download the mongo library so that you can start interacting with it
{
"require": {
"mongodb/mongodb": "^1.1"
}
}
Once your done with that you will have a vendor directory in your project folder which contains the autoload.php which will handle auto loading of the necessary and dependency libraries required in Vendor.
You can start using the library as follows
db_connect.php
<?php
/* Require the Vendor for autoloading MongoDb Client */
include_once 'vendor/autoload.php';
/* Create the Object of Mongodb */
$mongoDB = new MongoDB\Client;
/* Creating the database on which I will be working */
$erpDB = $mongoDB->database_name;
You can use the above code as follows
products.php
<?php
include_once 'DB/db_connect.php';
/* The following creates the products collection */
$productsCollection = $erpDB->products;
$insertedData = $productsCollection->insertOne(
['_id' => $idCounter, 'product_name' => $productName, 'product_quantity' => $productQuantity]
);

`BulkWrite error :: norepl` mongodb php BulkWrite

I getting this is exception in my application, and don't understand why. This exception throw in for one collection, over collection not throw this exception, with processed insert(),update(), or delete()
/**
* insert to mongo db method
* #param $dataArray
* #param $collection
*/
static function insert($dataArray, $collection) {
$connect = Core_Model_Mongo::getConnect();
$write = new MongoDB\Driver\BulkWrite();
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
$write->insert($dataArray);
$connect->executeBulkWrite(
Config_Db::getConf()['mongodb']['db'].'.'.$collection,
$write,
$writeConcern
);
}
end get connect method
/**
* #return \MongoDB\Driver\Manager
*/
static function getConnect() {
if(!is_null(self::$_connect)) {
return self::$_connect;
}
self::$_connect = new \MongoDB\Driver\Manager(Config_Db::getConf()['mongodb']['connect']);
return self::$_connect;
}
data save in collection success full, and this exception not take insert(),update() and other methods. I temporary resolve this question by try catch block
try {
// my code
} catch(MongoDB\Driver\Exception\BulkWriteException $error) {
Core_App::log(var_export($error,true));
}
but this is resolve not correct because I need application without any exception,error,notice, and over log level error.

Best way to access config for PDO database class with dependency injection

I am learning how to use PDO and writing a Database class for the first time. I have read for a few hours about this subject and found some useful information here, here and here.
It seems clear that dependency injection is the right strategy, but I'm not sure on the best way to have the Database class access the configuration details for the database (host, dbname, user, pass).
In the first two examples above, this information is included inside the Database class. However, I usually keep all my global configuration variables inside an external file such as config.php.
In the last example, user 'prodigitalson' adds this comment to his getInstance() method:
// get the arguments to the constructor from configuration somewhere
Since the constructor for this Database class includes parameters for the database configuration, I assume that this information is not supposed to be stored in the Database class itself.
So what is the best strategy for accessing the database configuration (which I am currently storing in config.php along with other config variables) from the getInstance() method?
Someone asked a similar question here but none of the answers really addresses the question, imo.
As I said in the comments, you are using the singleton pattern which is not dependency injection.
Here is an example using dependency injection:
class Database
{
public function __construct($host, $user, $password) {
// ...
}
}
$db = new Database('foo', 'bar', 'baz');
Then you inject the database object in the classes where you need to use it:
$reportGenerator = new ReportGenerator($db);
Have a look at this tutorial if you are still lost.
While this is not what I would prefer, because \PDO does not lend itself to being configured after construction, it is the closest I've come to getting DI with \PDO.
<?php namespace b01\Database;
use Exception;
use b01\DatabaseException;
use PDO;
use PDOException;
/**
* This class is responsible for connecting to a Database.
* It wraps the PDO object, setting all the values needed in order to connect.
* Also displays some human readable error messages when connecting fails.
*
* #package \b01\Database
*/
class Connection
{
/**
* string
*/
const DSN_MYSQL = 'mysql:dbname=%s;host=%s;port=%s';
/**
* Initialized the PDO transport object.
*
* It was decided to pass the PDO class in as a string, as pseudo DI,
* to make the class more testable.
*
* #param string $server server.
* #param string $database Database name.
* #param string $username Database username for reading.
* #param string $password Database username password.
* #param int $port Server port number.
* #param string $pdoClass Defaults to \PDO, but is passed in this way to
* make this class more testable.
* #throws \b01\Exceptions\DatabaseException
*/
public function __construct(
$server,
$database,
$username,
$password,
$port = 3306,
$pdoClass = '\PDO'
) {
$dsn = sprintf(
self::DSN_MYSQL,
$database,
$server,
$port
);
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
];
try {
$this->connection = new $pdoClass($dsn, $username, $password, $options);
} catch (Exception $error) {
throw new DatabaseException(
DatabaseException::CODE_CONNECT,
[$dsn . "\n\n", $error->getMessage()]
);
} catch (PDOException $error) {
throw new DatabaseException(
DatabaseException::CODE_CONNECT,
[$dsn . "\n\n", $error->getMessage()]
);
}
}
In your config.php file, set some constants for your database credentials, depending on the server you are running in:
switch($_SERVER['HTTP_HOST']){
case 'your-live-domain.com':
define('MYSQL_HOST', '<input>');
define('DB_NAME', '<input>');
define('MYSQL_USER', '<input>');
define('MYSQL_PW', '<input>');
break;
default:
// perhaps this could be your localhost db credentials
define('MYSQL_HOST', '<input>');
define('DB_NAME', '<input>');
define('MYSQL_USER', '<input>');
define('MYSQL_PW', '<input>');
}
Then, you can make calls to these constants within your database connection class(es).

Parsing WSDL: Couldn't Bind to Service

Presently, I am trying to interface with a SOAP-based camera system to tie into its action API so I can control when its lights come on programatically and so forth. However, when I use the code below, it's saying it cannot bind to the service and doesn't seem to be able to properly digest the WSDL file associated with the API, which can be found here:
http://www.axis.com/vapix/ws/action1/ActionService.wsdl
Is there something that's wrong with my code, or is this an issue with the WSDL file itself? Thank you very much in advance for the assistance! In advance, the error generating is the following, generated at the instantiation of the SoapClient object in the constructor:
SOAP-ERROR: Parsing WSDL: Couldn't bind to service
<?php
/**
* The purpose of this class is to act as a means to interface with a Vapix camera
* using SOAP requests so that events may be broadcast to it.
*/
$vapix = new Vapix("http://www.axis.com/vapix/ws/action1/ActionService.wsdl",
"<http://camera.address.edu>",
"<username>", "<password>");
if ($vapix)
{
echo "Connection to VAPIX successful!\n";
}
else
{
echo "Connection to VAPIX unsuccessful!\n";
}
/**
* The constructor takes in a WSDL address, the actual interfacing address of the
* server we are connecting to, a username, and a password, and establishes the
* SOAP client we need to interface with said address.
*
* #param $wsdl The WSDL specification for the service we are interacting with.
* #param $address The actual server address we are interfacing with.
* #param $username The username we need to access the server.
* #param $password The password we need to access the server.
*
* #return New Vapix object ready to interface with SOAP service.
*/
class Vapix
{
// the soap client variable we will be using to store our Vapix connection
private $soapClient;
public function __construct($wsdl, $address, $username, $password)
{
try
{
$soapClient = new SoapClient($wsdl, array("soap_version" => SOAP_1_2));
}
catch (SoapFault $fault)
{
echo "Error instantiating SOAP object!\n";
echo $fault->getMessage() . "\n";
}
// prepare SOAP headers
$sh_param = array(
"username" => $username,
"password" => $password
);
$headers = new SoapHeader($address, "UserCredentials", $sh_param);
// prepare SOAP client
$soapClient->__setSoapHeaders(array($headers));
}
/**
* This function is a generalized function used for calling a SOAP request to
* whatever service or server we are linked up to (in this case a VAPIX camera)
* so that other more specialized functions can derive from it. It will take in
* the name of the function, as well as a list of parameters.
*
* #param $funcName The name of the function we want to call.
* #param $parameters The parameters for the function we want to call.
*
* #return $info Returns info from the call if successful, NULL otherwise.
*/
public function callSoapFunction($funcName, $parameters)
{
try
{
$info = $soapClient->__call($funcName, array($parameters));
}
catch (SoapFault $fault)
{
print(
"alert('Sorry, blah returned the following ERROR: " . $fault->faultcode . "-" .
$fault->faultstring.". We will now take you back to our home page.');
window.location = 'main.php';"
);
return NULL;
}
if ($error == 0)
{
return $info;
}
}
}
?>
At least the provided WSDL-file has no <service>-area at the end of the wsdl-definition right after the <binding> block. But this missing <service>-block is needed as it contains concrete servicespecific informations (for instance its webservice URL/endpoint is listed there).

PDO refuses to switch between multiple Databases!

Please I am very new to PDO, rather a novice at PHP as well. I am currently working on a project that involves connections to many databases: MySQL, MSSQL and Oracle. So I am using the class below, with PDO, for my connection. The class code is below.
class db {
private static $objInstance;
/*
* Class Constructor - Create a new database connection if one doesn't exist
* Set to private so no-one can create a new instance via ' = new DB();'
*/
private function __construct() {}
/*
* Like the constructor, we make __clone private so nobody can clone the instance
*/
private function __clone() {}
/*
* Returns DB instance or create initial connection
* #param
* #return $objInstance;
*/
public static function getDB($DBtype, $DBindex) {
include('vars.inc.php');
if (!self::$objInstance){
$DBid = $DBindex - 1;
switch ($DBtype){
case "mysql":
self::$objInstance = new PDO("mysql:host=".$dbvars[$DBid][0].";dbname=".$dbvars[$DBid][1], $dbvars[$DBid][2], $dbvars[$DBid][3]);
break;
case "mssql":
self::$objInstance = new PDO("odbc:Driver={SQL Server};Server=".$dbvars[$DBid][0].";Database=".$dbvars[$DBid][1], $dbvars[$DBid][2], $dbvars[$DBid][3]);
break;
case "oci";
self::$objInstance = new PDO("oci:dbname=//".$dbvars[$DBid][0].":".$dbvars[$DBid][4]."/".$dbvars[$DBid][1], $dbvars[$DBid][2], $dbvars[$DBid][3]);
break;
// Add other case(s) here if another RDBMS (Relational Database Management system) is used
default:
break;
}
self::$objInstance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$objInstance;
}
}
And here is the vars include file that is required by the class, I used an array cos I felt this way, new databases can be added easily to the vars file by a non-programmer over time. Of course, here, I have changed the var file values.
define('DB_SERVER', 'localhost');
define('DB_NAME', 'db1name');
define('DB_USER', 'root');
define('DB_PASSWORD', 'rootpass');
define('DB_PORT', '');
define('DB2_SERVER', 'xxx.xxx.xx.xxx');
define('DB2_NAME', 'db2name');
define('DB2_USER', 'root2');
define('DB2_PASSWORD', 'rootpass2');
define('DB2_PORT', '');
define('DB3_SERVER', 'xx.xxx.xxx.xxx');
define('DB3_NAME', db3name');
define('DB3_USER', 'root3');
define('DB3_PASSWORD', 'rootpass3');
define('DB3_PORT', '');
define('DB4_SERVER', 'xxx.xx.xxx.xx');
define('DB4_NAME', 'oracledb');
define('DB4_USER', 'root4');
define('DB4_PASSWORD', 'rootpass4');
define('DB4_PORT', '1521');
$dbvars = array( array(DB_SERVER, DB_NAME , DB_USER, DB_PASSWORD, DB_PORT),
array(DB2_SERVER, DB2_NAME , DB2_USER, DB2_PASSWORD, DB2_PORT),
array(DB3_SERVER, DB3_NAME , DB3_USER, DB3_PASSWORD, DB3_PORT),
array(DB4_SERVER, DB4_NAME , DB4_USER, DB4_PASSWORD, DB4_PORT)
);
Now the problem is that, whenever I have connected to one database and try to run my queries on another one, PDO keeps remembering the old database. But if I independently run either query, everything is fine. Can someone please help with this, or suggest a better method? :(
E.g.
include('./includes/db.class.php');
try {
$result = DB::getDB("mysql", 3)->query("SELECT myrow FROM mytable");
foreach($result as $row){
print $row['myrow'].'<br />';
}
}catch(PDOException $e){
echo $e->getMessage();
}
echo "<br />Then<br /><hr /><br />";
try {
$result = DB::getDB("mysql", 1)->query("SELECT yourrow FROM yourtable");
foreach($result as $row){
print $row['yourrow'].'<br />' ;
}
}catch(PDOException $e){
echo $e->getMessage();
}
In this case, PDO will simply keep checking DATABASE db1name for TABLE yourtable rather than check DATABASE db3name. So PDO will throw an error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db1name.yourtable' doesn't exist
You have it setup as a singleton. So your next call to Db::getDB returns the original instance. If you want to cache the instances for the duration of the script, change $objInstance to an array, and then instead of doing:
if (!self::$objInstance){
Do
$signature = $DBtype . $DBindex;
if (!isset(self::$objInstances[$signature])) {
Of course you'll need to change the assignment lines and the return line as well, but I think you get the idea...
It appears that your getDB function will only connect once because of this line:
if (!self::$objInstance){
So the first time you execute it, it will connect, but on all subsequent calls the logic is ignored.
I suggest adding another property to your class that stores the current DBType and changing your conditional to:
if (!self::$objInstance || $DBtype != self::$dbtype){
You would have to set $dbtype inside each case of the switch statement.

Categories