How to access object outside of class - php

I'm trying to access an object outside of a class. I already have a class called Database which has a series of functions in it.
$database = new Database($host,$user,$pass,$name);
class User {
function view($username) {
$user = $database->findFirst('User','username',$username);
}
}
I cannot work out how to access the $database object and keep getting an error saying Undefined variable.

You could make use of dependnecy injection - constructor injection, e.g.
class User
{
/**
* #var Database
*/
protected $db;
public function __construct(Database $database)
{
$this->db = $database;
}
public function view($username)
{
$user = $this->db->findFirst('User', 'username', $username);
}
}
$database = new Database(/* ... */);
$user = new User($database);
Regarding the question in comment: Yes, this is possible. Let's think about some basic (abstract) class that could be used as a parent for all classes that should share the same basic logic (e.g. connecting to a DB, or at least injecting a DB connection).
Such abstract class could be:
class DBObject
{
/**
* #var Database
*/
protected $db;
public function __construct(Database $db)
{
$this->db = $db;
}
}
Then our User class can extend this abstract class in this way:
class User extends DBObject
{
public function view($username)
{
$user = $this->db->findFirst('User', 'username', $username);
}
}
Keep in mind that though the abstract class can implement __construct() function, it cannot be directly instantiated. Then somewhere in the code You can do the very same as in first example:
$database = new Database(/* ... */);
$user = new User($database);
$post = new Post($database);

$database should be a class member. Try this:
$database = new Database($host,$user,$pass,$name);
class User {
protected $db;
public function __construct($database) {
$this->db = $database;
}
public function view($username) {
$user = $db->findFirst('User','username',$username);
}
}

Simply define it as global variable within the function. Yet the proper way would be to make constructors or extend it with Database class.
$database = new Database($host,$user,$pass,$name);
class User {
function view($username) {
global $database;
$user = $database->findFirst('User','username',$username);
}
}
P.S. Here is another post where you can see the same situation with this solution.

Related

PHP oop inheritance of PDO connection to mysql database

I created two classes , USER and ADMIN, and admin extends user.
I am able to get which ever data i need from the database when using object of class USER but i cant get any data when working with the ADMIN object.
the classes are as follows:
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
...some functions to query the DB
}
and
class ADMIN extends USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
...some other functions to query the DB
}
at first i didn't include the constructor since i read that admin will inherit every not private property so this is my second try but in both cases i got this error:
Call to a member function prepare() on a non-object
any idea what am i missing ? thx
UPDATE: i have this function for example in ADMIN class:
public function getAppeals($user_id){
$stmt = $this->conn->prepare("SELECT * FROM appeals WHERE lecturer_id = :lecturer_id");
$stmt->execute(array(':lecturer_id' => $user_id));
$userRow = $stmt->fetchall(PDO::FETCH_ASSOC);
return $userRow;
}
the row that generates the error is this:
$stmt = $this->conn->prepare("SELECT * FROM appeals WHERE lecturer_id = :lecturer_id");
This should explain your issue http://php.net/manual/en/language.oop5.visibility.php
A private property is only visible in the class in which it was defined. However, making it protected will allow it to be accessed from any class that extends USER so it will be visible to ADMIN assuming you run the parent constructor from the ADMIN class like this parent::__construct();
If you make these changes it should work
class USER
{
//private $conn;
protected $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
...some functions to query the DB
}
class ADMIN extends USER
{
public function __construct()
{
parent::__construct();
}
public function getAppeals($user_id){
$stmt = $this->conn->prepare("SELECT * FROM appeals WHERE lecturer_id = :lecturer_id");
$stmt->execute(array(':lecturer_id' => $user_id));
$userRow = $stmt->fetchall(PDO::FETCH_ASSOC);
return $userRow;
}
}

PDO connect to db with classes

Im making a PDO system and got a problem/question. I gonna make multiple classes for my codes, for users, products etc. And I was wondering about the connection. I have this in one of my classes:
class Database
{
private $_db;
function __construct($db)
{
$this->_db = $db;
}
}
$db comes from a config file, where I also load all the classes in. The question is now:
Do I have to create the same function in all the classes or can i just have my "database" class that work for all my classes?
No, you don't have to (and shouldn't) create the same function over and over again for every class. That makes it very hard to maintain your application.
Try one of the following methods:
1. Dependency Injection
You can use dependency injection to do this. This is very situational and probably not what you're looking for, but I thought I'd put it here anyway.
Assume the following:
class Database
{
/**
* #var PDO
*/
private $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
}
class User
{
/**
* #var Database
*/
private $db;
// Here we inject a Database object (as hinted by Database $db) into the current instance
public function __construct(Database $db)
{
$this->db = $db
}
}
try
{
$pdo = new PDO(...);
$db = new Database($pdo);
}
catch(PDOException $ex)
{
// Could not connect to database or some other error message
}
// Inject $db in the user class
$user = new User($db);
2. Singleton
You can make your Database class a singleton and then call it statically. This might be more what you need.
class Database
{
/**
* #var Database
*/
private static $instance;
/**
* #var PDO
*/
private $db;
protected function __construct(PDO $db)
{
$this->db = $db;
}
// You'd call this in your config
public static function initialize(PDO $db)
{
if(self::$instance == null)
{
// Create a new instance of this class
self::$instance = new self($db);
}
}
// Get the instance
public static function getInstance()
{
return self::$instance;
}
// Do something
public function doSomething()
{
// Do something
echo "Foo";
}
}
class User
{
public function doSomething()
{
// This would print "Foo"
Database::instance()->doSomething();
}
}
try
{
$db = new PDO(...);
}
catch(PDOException $ex)
{
// Could not connect to database or some other error message
}
Database::initialize($db);
$user = new User();
Hope this helps.

PHP __construct()

I have the following, however I'm unable to access the database functions outside of the initial db class?
Thanks!
database.php
class db
{
private $connection;
public function __construct()
{
$this->connection = new PDO();
}
}
admin.php
class admin
{
private $connection
public function __construct(db $connection)
{
$this->connection = $connection;
}
function myFunc()
{
// How do I access the connection here?
}
}
main.php
//include db.php
//include admin.php
$connection = new db();
$admin = new admin($connection);
// How do I access the DB here?
First of all, why are you encapsulating PDO just to class containing that one object? Cannot you use PDO directly?
One of the common practices would be to implement getter in db class, like:
class db {
...
public function getPDO(){
return $this->connection;
}
}
Another way is to re-implement every function (why would you do that?!), or use __call magic function...
Or just make $connection public ;)
Or you could extend PDO class (I'm not sure whether it'll work):
class DB extends PDO {
public function __construct ( $dsn, $username = null, $password = null, $driver_options = array()){
parent::__construct( $dsn, $username, $password, $driver_options);
... more of your stuff
}
public function myFunc(){
$this->...
}
}
ok, you really need to go and read up on object-oriented design, and access modifiers. I'll explain what you need to do here, but this is a band-aid solution, and you need to deeply understand how things are working here.
In your admin class, you defined the connection as a private attribute of the class. So in the myFunc function, you simply do $this->connection to access the connection that you created in the constructor.
In your main.php file, the object you are getting rom initializing a DB object is not the connection. It is the db object as a whole, so you can not pass the connection by itself to the admin class (it is defined as private, so nobody outside the class can view it). However, why do you need to pass it to the admin class? Managing the DB connection should be the responsibility of the DB class.
In other words, what are you trying to achieve by exposing the DB connection to the admin class?
Upate: based on the reply here is a suggested answer:
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO();
}
}
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function myFunc() {
$this->db->query('...');
}
}
In your main.php file:
$admin = new Admin();
$admin->myFunc();
Keep in mind, every admin object is going to create a new connection to the DB, so if you create many admin objects you might face some issues. You can get around this by declaring the DB to be a singleton.
How about this:Updated
<pre>
<?php
class DB {
private $host;
private $user;
private $pass;
private $dbase;
private $connection;
public function __construct($host,$user,$pass,$dbase)
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->dbase = $dbase;
$this->connection = new PDO("mysql:host=$this->host;dbname=$this->dbase", $this->user, $this->pass);
}
public function connect()
{
return $this->connection;
}
public function close()
{
unset($this->connection);
return true;
}
}
$dbh = new DB('localhost','root','','inventory');
$result = $dbh->connect()->query("SELECT * FROM products")->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
?>
</pre>
Updated with files separation
database.php
class db
{
private $connection;
public function __construct()
{
$this->connection = new PDO();
}
}
admin.php
class admin
{
private $connection
public function __construct(db $connection)
{
$this->connection = $connection;
}
function myFunc()
{
return $this->connection->prepare('SQL');
}
function getConnection()
{
return $this->connection;
}
}
main.php
require_once 'database.php';
require_once 'admin.php';
$connection = new db();
$admin = new admin($connection);
$admin->myFunc()->execute();

How to use $db instead of $GLOBALS['db'] in my classes?

I need to use $GLOBALS['db'] in my classes ($db is defined in my index.php), but I don't want to use $GLOBALS['db'] when I have to call it.
I wrote this code at the beginning of my classes :
class ClassName
{
var $db;
public function __construct()
{
$this->db = $GLOBALS['db'];
}
public function test()
{
$val = $this->db->oneValue('SELECT first_name FROM users LIMIT 0, 1');
echo $val->first_name;
}
}
But I'm not enjoying this; I prefer to use directly $db in my code. Is there a solution to be able to call $GLOBALS['db'] by $db?
Simples, just inject in the constructor or a setter method: (I'm assuming $db is an object here, not an array of connection parameters etc)
class ClassName
{
protected $db;
public function __construct($db)
{
$this->setConnection($db);
//Any other constructor things you want to happen...
}
/*
* This is just here for convenience, this could be protected if you only want to set
* the db connection via the constructor
*/
public function setConnection($db)
{
$this->db = $db;
}
public function test()
{
$val = $this->db->oneValue('SELECT first_name FROM users LIMIT 0, 1');
echo $val->first_name;
}
}
As mentioned in some comments above, this is a form of dependency injection which will give you more ability to re-use code inside your project (A Good Thing TM).
I prefer using singleton pattern for databases.
this is the DB class i am using for my app.
class Database {
protected static $_dbh;
const HOST = 'localhost';
const DATABASE = 'dbname';
const USERNAME = 'username';
const PASSWORD = 'password';
private function __construct() { }
public static function getInstance() {
if(!isset($_dbh)) {
try {
#Connection String.
self::$_dbh = new PDO('mysql:host='.self::HOST.';dbname='.self::DATABASE,self::USERNAME,self::PASSWORD);
self::$_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
#Print Errors.
echo $e->getMessage();
}
}
return self::$_dbh;
}
}
as i am using singleton pattern the connection will be re-used. you can now use the connection everywhere in your app by calling static connection method i.e
class ClassName
{
protected static $_dbh;
public function __construct() {
self::$_dbh = Database::getInstance();
}
public function test() {
$sth = self::$_dbh->query('SELECT first_name FROM users LIMIT 0, 1');
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $row['first_name'];
}
}

Calling a class inside another one in PHP

Hope you can help me with this one: i have two classes: Database and Users. The Database connects to the database using PDO (inside the constructor) and has functions to alter tables, insert data, etc. The Users class will handle login, as well add/remove users. However, the Users class needs to connect to the database. How can i do this?
There are several things you could do:
Globals
$db = new Database();
class Users
{
public function foo()
{
global $db;
$db->query();
}
}
Setting a static variable
$db = new Database();
class Model
{
static public $db;
}
Model::$db = $db;
class Users extends Model
{
public function foo()
{
self::$db->query();
}
}
Use a singleton
class Database
{
private static $instance;
private function __construct()
{
}
public static function instance()
{
return self::$instance ? self::$instance : self::$instance = new self();
}
}
class Users
{
public function foo()
{
Database::instance()->query();
// or $db = Database::instance(); $db->query();
}
}
The one thing you want to avoid is creating a new database connection per model or class.
Same way you normally would, but it might help to make the database a class property:
<?php
class Users
{
protected $_db;
public function __construct(Database $database = null)
{
if (!$database) {
$database = new Database;
}
$this->_db = $database;
}
public function addUser($username)
{
// Do stuff ...
$this->_db->insert($data);
}
}
Then you can use the User class like:
<?php
$users = new Users;
$users->addUser('joebob');
Simply add a reference to the database class instance into Users:
class Users {
var $database;
function __construct() {
$this->database = new Database();
}
};
Alternatively, if Database is a singleton, just reference it directly.
One way to do so would be to create ONE shared instance of the database class, then use it as a global variable wherever needed.
Start by creating the instance anywhere in your project, just make sure it is in global space (not inside another class or function).
$DB = new Database();
Then to access the shared database object, just use the $GLOBALS built-in array:
class User {
function __construct() {
$DB = &$GLOBALS['DB'];
// do something
$DB->callSomeMethod();
}
...
}
As pointed out by #Ryan, namespace collisions are possible using this strategy. The best middle path out would be to convert the Database class into a singleton. Then it would store its own instance (translation: ONE connection no matter what) which could be accessed via a Database::getInstance() method.
This is my Users class:
class Users {
private $data;
private $db;
public function __construct() {
$db = Database::getInstance('localhost', 'database', 'root', '123456');
}
public function __get($key) {
return $this->data[$key];
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function test() {
foreach($this->db->query('table', '*', '', '', '', '', '0,5') as $value) {
$results .= $value['field1'] . "<br />";
}
return $results;
}
}

Categories