PHP calling a method from outside another class - php

Not sure of OOP syntax to do this...
I'd like to have aclass that calls the mysqli object
class Voovid_DB {
private $host = 'localhost';
private $user = 'blahblah';
private $password = 'blahblah';
private $name = 'blahblah';
public function __contstuct(){
$dbh= new mysqli( $this->host, $this->user, $this->password, $this->name );
return $dbh;
}
//get and set methods for host, user etc... go here
}
now I'd like to access all the mysqli methods like so
$dbconnect = new Voovid_DB();
if ( $result = $dbconnect->query( "SELECT first_name, last_name FROM members WHERE member_id=9" ) ) {
while ( $row = $result->fetch_assoc() ) {
$first_name = ucfirst( $row['first_name'] );
$last_name = ucfirst( $row['last_name'] );
}
} else {
$errors = $dbconnect->error;
}
i'm new to PHP OOP and not sure how to get to the mysqli methods inside the Voovid_DB class

You have to either extend the MySQLi class, or build a proxy around it.
The easiest is probably to extend it:
class Voovid_DB extends MySQLi {
private $host = 'localhost';
private $user = 'blahblah';
private $password = 'blahblah';
private $name = 'blahblah';
public function __construct(){
// call parent (MySQLi) constructor
parent::__construct( $this->host, $this->user, $this->password, $this->name );
}
// no need for other methods, they already are there
}
Notice the extends MySQLi.
Then your second code snipet should work.
Or, build a proxy:
class Voovid_DB {
private $host = 'localhost';
private $user = 'blahblah';
private $password = 'blahblah';
private $name = 'blahblah';
private $dbh;
public function __construct(){
$this->dbh = new MySQLi($this->host, $this->user, $this->password, $this->name);
}
// this will proxy any calls to this class to MySQLi
public function __call($name, $args) {
return call_user_func_array(array($this->dbh,$name), $args);
}
}

You could define a __call method:
public function __call($method, $arguments) {
return call_user_func_array(array($this->dbh, $method), $arguments);
}
__call is invoked if an undefined or inivisible method is called.

you code is correct.
the only thing you have to do is to make sure that you define your functions in Voovid_DB as public.
private or protected methods cannot be accessed from other classes
store your mysqli object in a public field in your class then you can access it like this:
$dbconnect->mysqlField->query

Constructors aren't supposed to return anything. When you say $dbconnect = new Voovid_DB(); you would normally be trying to create a Voovid_DB object, but it looks like you're using it to try an make a mysqli object. Don't make this the constructor and call the function after you create the voovid_db object.
$obj = new voovid_DB();
$dbConnect = $obj->createMysqli();

Related

Using class database connection in other class

I have a class with a connection to a database
$db = new db();
class db {
public $server = 'localhost';
public $user = '';
public $passwd = '******';
public $db = '';
public $dbCon;
function __construct() {
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db);
}
function __destruct() {
mysqli_close($this->dbCon);
}
}
Now i want to make an other class and using the connection like this:
class Categories (
function GetCategory($cat) {
$myQuery = "SELECT * FROM test GROUP BY $cat";
$results = mysqli_query($this->dbCon, $myQuery);
return $results;
}
)
How can i use the connection in a other class?
Can somebody help me out whit this?
Make the $dbCon in your db class a static variable, so you can access it from category's using db::$dbcon as the connection variable. You could also make a static function returning the static dbcon variable, usefull tot check if it is actually a link and not null.
This is just one solution of many possibilities, but probably the easiest to implement because it isn't likely you need more connections to a db, so a static is perfect for it.
A static is nothing more then a variable living in the namespace it is defined in, you don't need to initialize the class in order to access it. It's value is shared across all instances of the object, so creating multiple DB class instances allows you tot just return a static if it was set in a previous DB class instance.
class db{
static $link;
static function connect(){
if(self::$link = mysqli_connect(....)){
return self::$link;
} else {
die('could not connect to db');
}
}
static function getcon(){
return isset(self::$link) ? self::$link : self::connect();
}
}
class Categories{
function GetCategory($cat){
$myQuery = "SELECT * FROM test GROUP BY $cat";
return mysqli_query(db::getcon(), $myQuery);
}
}
Create an object of the db class in the categories class. Then use that object to query the db accordingly. Also make sure you use a static variable in the db class. SO that the connection variable is created once and will be used all along the application.
Your db class may look like this
class db {
public $server = 'localhost';
public $user = '';
public $passwd = '******';
public $db = '';
public static $dbCon;
function __construct() {
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db);
}
function __destruct() {
mysqli_close($this->dbCon);
}
}
Your categories class may look like this
class Categories {
$connection=db::$dbCon;
if(!$connection){
$db=new db();
$connection=db::$dbCon;
}
function GetCategory($cat) {
$myQuery = "SELECT * FROM test GROUP BY $cat";
$results = mysqli_query($this->connection, $myQuery);
return $results;
}
}

How to properly use dependency injection with PHP?

I'm very new at PHP. I have two classes: Database and RetrieveItem. Because RetrieveItem needs a connection, I've just been extending the Database class to use its constructor. Apparently this is wrong, because RetrieveItem is not a database?
Here is my current code:
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem extends Database {
function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
And on a separate page, to use this, I have:
include 'db.php';
$retrieve = new RetrieveItem();
print_r($retrieve->retrieve_item());
Rather than extend the class, how can I access the Database constructor in the cleanest possible way?
Any help or guidance would be much appreciated.
This amended code is still not working:
Argument 1 passed to RetrieveItem::__construct() must be an instance of Database, none given:
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem {
private $_db;
public function __construct(Database $database){
$this->_db = $database;
}
public function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
In use:
include 'db.php';
$database = new Database();
$retrieve = new RetrieveItem($database);
print_r($retrieve->retrieve_item());
As you said, with plain dependency injection
class RetrieveItem {
private $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
For easier use, you can abstract the injection in container, or, at least, has one super class that recieves the injection.
A dependency injection is so easy but it sounds complicated.
$class1 = new firstclass();
$class2 = new secondclass($class1); //This is a dependency injection.
class firstclass{
private $var1;
private $var2;
public function __construct(){
$this->var1 = "hello";
$this->var2 = "world";
}
public function getvar1(){
return $this->var1;
} //imagine a second one like this for var2;
}
class secondclass{
private $fc; //will hold first class object or the dependency.
public function __construct($firstclassobject){
$this->fc = $firstclassobject;
echo $this->fc->getvar1(); //call dependency methods like this.
echo $this->fc->getvar2();
} //echoes helloworld
}
So you pretty much put an object of one class and asign it to a field in your other class.
for your edit
set this line in your database class at the top.
public connect; //add to dbclass
Then do this in your function
public function retrieve_item(){
$connect = $this->db->connect; //added this
$query = $connect->prepare("SELECT * FROM posts"); //changed this
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
class Database {
public $host = '127.0.0.1';
public $username = 'root';
public $password = '';
public $dbname = 'example';
public $connect;
function __construct(){
$this->connect = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
}
}
class RetrieveItem {
private $connect;
public function __construct(&$db){
$this -> connect = $db -> connect;
}
function retrieve_item(){
$query = $this->connect->prepare("SELECT * FROM posts");
$query->execute();
$all_items = $query->fetchAll(PDO::FETCH_ASSOC);
return $all_items;
}
}
// Usage
$db = new Database();
$retrieve_item = new RetrieveItem($db);
Here in Retrieve Item we tried to send the database object as a refereneced variable rather sending a copy of its, which happens to be a good way of passing connection to your operable classes

Call to a member function on a non-object

I am new to php oop , so struggling a bit .
i have a database connection class viz :
class config{
protected $HOST = "localhost";
protected $USERNAME = "something" ;
protected $PASSWORD = "something";
protected $DATABASE = "something";
// Constructor - open DB connection
function __construct() {
try {
$this->db = new mysqli($this->HOST, $this->USERNAME, $this->PASSWORD, $this-
>DATABASE);
$this->db->autocommit(FALSE);
}
catch(Exception $e)
{
if($this->db->connect_errno > 0){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
// Destructor - close DB connection
function __destruct() {
$this->db->close();
}
}
$api = new Config();
Now i have another class from which i need to perform some tasks ...but i get FATAL error .
second class :
class Myclass extends config {
function __construct(){}
public function myfunction()
{
try{
$stmt = $this->db->stmt_init(); /* Error here : Fatal error: Call to a member
function stmt_init() on a non-object */
$query = "SELECT ABC FROM table " ;
$stmt = $this->db->prepare($query); /* Error here : Fatal error: Call to a member
function prepare() on a non-object */
}
catch(){}
}
}
Please guide me with proper remedial code snippet
In your child class, you need to call the parent constructor. PHP won't automatically call parent constructor's when a child class is instantiated.
class Myclass extends config {
function __construct($h, $u, $p, $d){ parent::__construct($h, $u, $p, $d); }
Also, you don't have a $db property in the parent class, so add that
class config{
protected $db;
protected $HOST = "localhost";
protected $USERNAME = "something" ;
protected $PASSWORD = "something";
protected $DATABASE = "something";
Edit: Dependency Injection approach:
class config{
public $HOST = "localhost";
public $USERNAME = "something" ;
public $PASSWORD = "something";
public $DATABASE = "something";
}
class Myclass
{
protected $db;
function __construct($db)
{
$this->db = $db;
}
public function myfunction()
{
// do whatever with $this->db
}
}
$config = new Config();
try
{
$db = new mysqli($config->HOST, $config->USERNAME, $config->PASSWORD, $config->DATABASE);
$db->autocommit(FALSE);
}
catch(Exception $e)
{
if($db->connect_errno > 0){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
$myclass = new Myclass($db);
Have a look into Dependency Injection. This is a favorable approach for dealing with classes that need access to a database. Instead of having all your classes extend the database, just pass the datsbase object as a parameter when creating new classes (that need the db).
Your derived class constructor is not calling the base constructor, so $this->db does not have the value it's supposed to. In PHP you must do this explicitly.
In this particular case, you should remove the derived constructor altogether since it's not doing anything. This will let PHP use the base constructor directly.

Using PDO database class within other PHP classes

I have a database class that uses PDO. Here's a portion example of it:
class db {
private $host;
private $username;
private $password;
private $con;
private $pdo;
public function __construct( $database = "dnname" )
{
$this->host = "localhost";
$this->username = "username";
$this->password = "pass";
$conStr = "host={$this->host};dbname={$database}";
try {
$this->pdo = new PDO( "mysql:$conStr", $this->username, $this->password );
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
echo "error ". $e->getMessage();
}
}
public function fetch_single_row($sql, $data)
{
if( $data !== null )
$data = array_values( $data ); // Incase it's an associative array
$sel = $this->pdo->prepare( $sql );
$sel->execute( $data );
$sel->setFetchMode( PDO::FETCH_OBJ );
$obj = $sel->fetch();
return $obj;
}
I would like to use this class and its functions (it has more than I've included) inside other classes.
I have tried many many different things, but the only thing that works so far is starting a new instance of db in every new class which I think is bad practice. For instance:
class cms {
function cms(){
$this->db = new db();
}
function is_admin($id) {
if($this->db->fetch_single_row("SELECT id FROM user WHERE id = ? LIMIT 1", array($id))){
return true;
} else {
return false;
}
}
in my index.php, I include these classes and use them:
include("db.class.php");
include("cms.class.php");
$cms = new cms();
if($cms->is_admin($id)){
//code here
}
What is the correct way to accomplish this?
Take a look into the Singleton Design Pattern, it works great for a DB class
I used to use a class like this for quite a while
abstract class DB
{
protected static $instance;
protected $db;
protected static $host = 'host';
protected static $user = 'user';
protected static $pass = 'pass';
protected static $database;
public static function getInstance()
{
if (!isset(self::$instance)) self::$instance = new static();
return self::$instance;
}
protected function __construct()
{
$this->db = new PDO(sprintf('mysql:host=%s;dbname=%s', static::$host, static::$database), static::$user, static::$pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function db()
{
return static::getInstance()->db;
}
public function fetch_single_row($sql, $data)
{
if( $data !== null )
$data = array_values( $data ); // Incase it's an associative array
$sel = self::db()->prepare( $sql );
$sel->execute( $data );
$sel->setFetchMode( PDO::FETCH_OBJ );
$obj = $sel->fetch();
return $obj;
}
}
I would then extend that class for each different database I would need to connect to
class Main extends DB
{
protected static $database = 'db';
}
You can then use the class like this
$db = Main::getInstance();
$obj = $db->fetch_single_row($sql, $data);

Sharing variables between classes when including files

stuck on this. Lets start with code.
Settings.php
class settings{
public $db_host;
public $db_username;
public $db_password;
public $db_database;
public function db_settings(){
/*$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_database = "eveonline";*/
$this->db_host = "localhost";
$this->db_username = "root";
$this->db_password = "";
$this->db_database = "eveonline";
}
This is where I want to use this
class xmlUpdate{
include_once ('./lib/settings.php'); //This wont work
public $itemCount;
public function dbItemCount(){
include_once ('./lib/settings.php');// This will work, but only in this function
In this case its for database varables, so I dont have to duplicate code whenever I want to make a database connection.
How can I use the database varables in another class, the whole class, not just the function where it allows me to include?
I would put the include into the __construct() function of your class, instantiate a new Class, read out the variables put them in local variables in your class.
class xmlUpdate{
public $db_host;
public $db_username;
public $db_password;
public $db_database;
function __construct(){
include_once('./lib/settings.php');
$settings = new settings();
$this->db_host = settings->db_host;
$this->db_username= settings->db_username;
$this->db_password= settings->db_password;
$this->db_database= settings->db_database;
}
}
Or you could make you xmlUpdate class extend the settings class.
This might be a possible approach, the Database class could also have connect and disconnect, query etc. function. Write a __autoload function so you don't have to include any files. Another simple approach would be to define all the data in the index.php -> define('DB_HOST', 'localhost'); and later access it via DB_HOST.
class DataBase {
private static $instance = null;
public $db_host;
public $db_username;
public $db_password;
public $db_database;
private function __construct() {
$this->db_host = "localhost";
$this->db_username = "root";
$this->db_password = "";
$this->db_database = "eveonline";
}
private function __clone() {
}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new DataBase;
}
return self::$instance;
}
}
class Xml {
protected $db;
public function __construct() {
$this->db = DataBase::getInstance();
}
public function getUsername() {
return $this->db->db_username;
}
}
// test
$xml = new Xml;
print $xml->getUsername() . "\n";
you could make them static or follow a singleton pattern
I think that what you're trying to do is have some GLOBAL type of thing you can access from anywhere.
As the user busypeoples suggests, you could try using the singlton pattern if you want to include some complicated behavior for the database like connections. Look up the singleton pattern and you should definitely be able to find some PHP specific examples.
If all you want to do is share some simple connection string, password and user for the database then you can use the define statement.
//the db_info.php file
define( 'DB_NAME', 'mydevdatabase' );
define( 'DB_IP', '127.0.0.1' );
define( 'DB_USER', 'bob' );
define( 'DB_PASSWORD', 'password' );
Afterward, you can just include this file at the beginning of any PHP file and use the constants.
//some other php file
require_once( 'db_info.php' );
class Test
{
public function tester()
{
$some = DB_IP;
$other = DB_USER;
//your other code
}
public function otherfunction()
{
$some = DB_IP;
$other = DB_USER;
//your code
}
}

Categories