In my php project I've create 4 classes
CONNECTION
class Mysqliconn {
public $mysqli;
public function __construct(){
include "dbconfig.php";
$this->connect($host, $user, $password, $database, $charset);
}
public function connect (.....)
$this->mysqli = new mysqli(......);
}
}
UPLOAD
class Upload {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getID($id) {
echo $id;
}
}
USERS
class Users {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getName($name) {
echo $name;
}
}
CARS
class Cars {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getCars($cars) {
echo $cars;
}
}
In my php page I instantiate the classes in this way
function __autoload($class_name) {
if(file_exists('class/class.' . strtolower($class_name) . '.php')) {
require_once('class/class.' . strtolower($class_name) . '.php');
}
else {
throw new Exception("Unable to load $class_name.");
}
}
$db = new Mysqliconn();
$up = new Upload($db);
$us = new Users($db);
$cs = new Cars($db);
$cs->getCars('BMW');
$us->getName('Foo');
In my Cars Class I'd like to call method of classes Users and Upload.
Is it possibile to do? How could I do this? Thanks.
class Example{
public function __construct(){
$otherClass = new OtherClass();
$otherClass->functionInOtherClass();
}
}
or
class Example{
public function __construct($objFromOtherClass){
$objFromOtherClass->functionInOtherClass();
}
}
or
class Example{
public function __construct(OtherClass $objFromOtherClass){
$objFromOtherClass->functionInOtherClass();
}
}
If the object in question will be used throughout your Example class:
class Example{
protected $objFromOtherClass;
public function __construct(OtherClass $objFromOtherClass){
$this->objFromOtherClass = $objFromOtherClass;
}
public function test(){
$this->objFromOtherClass->functionInOtherClass();
}
}
You can call a public static function inside an other class:
class Users {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public static function getName($name) {
echo $name;
}
}
class Cars {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getCars($cars) {
echo $cars;
}
public function callGetName($name)
{
return Users:: getName($name) ;
}
}
Another option would be:
function callGetName($name)
{
$user = new Users();
$user->getName($name);
}
Related
Hey guys how can i assign PDO to my AbstractRepository class?
I got this error
#Fatal error: Uncaught TypeError: Cannot assign PDO to property #
class DataBase {
private $conn;
public static $instance;
private static $dsn = 'mysql:host=localhost;dbname=db';
private static $username = 'db';
private static $password = 'db';
public function __construct()
{
try {
$this->conn = new PDO(self::$dsn, self::$username, self::$password);
} catch (\PDOException $exception) {
echo 'Problem mit der Datenbankverbindung' . $exception->getMessage();
die();
}
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->getInstance()->conn;
}
}
abstract class AbstractRepository{
protected DataBase $connection;
public function __construct(){
$this->connection = DataBase::getInstance()->getConnection();
}
}
This is how you can return the Value of type PDO
class DataBase extends PDO{
public static $instance;
private static $dsn = 'mysql:host=localhost;dbname=db';
private static $username = 'db';
private static $password = 'db';
public function __construct()
{
try {
parent::__construct = new PDO(self::$dsn, self::$username, self::$password);
} catch (\PDOException $exception) {
echo 'Problem mit der Datenbankverbindung' . $exception->getMessage();
die();
}
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
abstract class AbstractRepository{
protected DataBase $connection;
public function __construct(){
$this->connection = DataBase::getInstance();
}
}
I have a problem. I have 2 classes (RouteController and BaseController). In the class BaseController i have my pdo connection included, and working. And in the class RouteController i have extend the BaseController and i want that the connection also works in the RouteController class. But if i make a var_dump() it returns NULL. How do i can make that it works?
Index.php:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
require_once 'App/Config.php';
require_once 'App/Controllers/BaseController.php';
require_once 'App/Controllers/RouteController.php';
require_once 'App/Controllers/DatabaseController.php';
$connection = new DatabaseController($config['database']['host'], $config['database']['user'], $config['database']['pass'], $config['database']['name']);
$connection = $connection->Connection();
new BaseController($connection);
new RouteController;
Here are the classes:
DatabaseController
<?php
class DatabaseController
{
private $host;
private $user;
private $pass;
private $name;
public function __construct($host, $user, $pass, $name)
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->name = $name;
}
public function Connection()
{
try {
$this->db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name, $this->user, $this->pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$this->db->exec("SET CHARACTER SET utf8");
return $this->db;
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
BaseController
<?php
class BaseController
{
protected $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
}
RouteController
<?php
class RouteController extends BaseController
{
public function __construct()
{
var_dump($this->connection); // Return NULL
}
}
I need some help please, thanks.
Sorry for my bad english.
try with this code:
<?php
class RouteController extends BaseController
{
public function __construct($connection)
{
parent::__construct($connection);
var_dump($this->connection); // Return NULL
}
}
$myObject = new RouteController($con);
UPDATE:
<?php
class BaseController
{
private $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function getConnection() {
return $this->connection;
}
}
class RouteController extends BaseController
{
public function __construct($connection)
{
parent::__construct($connection);
/* some other construct code */
}
}
$test = 'hello';
$myObject = new RouteController($test);
var_dump($myObject->getConnection());
this work
I found an issue I can't seem to find a solution to. I am using a singleton class / method that return a single static PDO object. When I try to declare a static reference to the object (http://i.imgur.com/EhKZuVH.png), I get http://i.imgur.com/jUPMQrO.png . How would I go about fixing this?
Game Class:
<?php
include_once('functions.php');
include_once('database.php');
$_codeRegex = '^([a-zA-Z0-9]{4,7})$';
class Game
{
public $Id = "";
public $Name = "";
private static $connection = Database::Connect();
public function __construct($id, $name)
{
$this->Id = $id;
$this->Name = $name;
}
}
?>
My singleton Class:
<?php
require_once('config.php');
CONST CONNECTION_FORMAT = 'mysql:host=%1$s;dbname=%2$s;charset=utf8';
class Database
{
private static $cont = null;
public function __construct() {
exit('Initialize function is not excessible.');
}
public static function Connect()
{
if (self::$cont == null)
{
try
{
$pdoConstuct = sprintf(CONNECTION_FORMAT, DB_SERVER, DB_NAME);
self::$cont = new PDO($pdoConstuct, DB_USER, DB_PASS);
self::$cont->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
}
catch(PDOException $e) { return false; }
}
return self::$cont;
}
public static function Disconnect()
{
self::$cont = null;
}
}
?>
PHP is not Java where you can define property values like this.
What you can do here is simply put property initialization into the contructor, like this:
private static $connection;
public function __construct($id, $name)
{
$this->Id = $id;
$this->Name = $name;
self::$connection = Database::Connect();
}
When you define a class property in PHP you can not set its default value to instance of a class.
I am a newbie to OOP. I have worked in procedural programming a lot. So i am in little trouble right now. Can you please tell me how to call an object of a class in another class and then i can access all the variables and function of that class with using that object.
For e.g
I have a class of DBconnection. i write my db queries in it. Now i have an other class named Users. Now i need to access the db queries in User class, definitely i need object of DBconnection class to access all db queries. What can i do please help
The example code which i have written is as below:
**DBConnection class**
class DBConnection
{
public $SITEURL;
public $servername;
public $username;
public $password;
public $dbname;
public $objDbConnect;
function DBConnection(){
$this->SITEURL=Configuration::SITEURL;
$this->servername=Configuration::servername;
$this->username=Configuration::username;
$this->password=Configuration::password;
$this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password);
if($this->objDbConnect){
mysql_select_db($this->dbname);
}
}
function InsertRecord($pStrTableName,$pArrField,$pArrValue)
{
$strSql="insert into $pStrTableName (";
$intFieldSize=count($pArrField);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.=$pArrField[$i];
}
else
{
$strSql.=$pArrField[$i].",";
}
}
$strSql.=") values (";
$intFieldSize=count($pArrValue);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.="'".$pArrValue[$i]."'";
}
else
{
$strSql.="'".$pArrValue[$i]."'".",";
}
}
$strSql.=")";
if(mysql_query($strSql))
{
return 1;
}
else
{
return 0;
}
}
}
**Users class**
class Users{
var $username,
$userpassword,
$email,
function User(){
}
}
The best way to do this would be to use Singleton pattern.
Following is an example
class DBConnection
{
private static $instance = null;
private function __construct() {
}
/*
* #return DBConnection
*/
public static function get_db()
{
if ( empty(self::$instance) ) self::$instance = new DBConnection();
return self::$instance;
}
public function query()
{
}
}
class User
{
function testfunc()
{
$db = DBConnection::get_db();
$db->query();
}
}
You can declare an object of your class in your second class and use it like
$c= new DBConnection();
$c->InsertRecord('Parameters here etc');
echo $c->username; //and other public variables similarly
DBConnection class
class DBConnection
{
public $SITEURL;
public $servername;
public $username;
public $password;
public $dbname;
public $objDbConnect;
function DBConnection(){
$this->SITEURL=Configuration::SITEURL;
$this->servername=Configuration::servername;
$this->username=Configuration::username;
$this->password=Configuration::password;
$this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password);
if($this->objDbConnect){
mysql_select_db($this->dbname);
}
}
function InsertRecord($pStrTableName,$pArrField,$pArrValue)
{
$strSql="insert into $pStrTableName (";
$intFieldSize=count($pArrField);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.=$pArrField[$i];
}
else
{
$strSql.=$pArrField[$i].",";
}
}
$strSql.=") values (";
$intFieldSize=count($pArrValue);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.="'".$pArrValue[$i]."'";
}
else
{
$strSql.="'".$pArrValue[$i]."'".",";
}
}
$strSql.=")";
if(mysql_query($strSql))
{
return 1;
}
else
{
return 0;
}
}
}
Users class
class Users{
var $username;
var $userpassword;
var $email;
var $dbcon;
public function __construct()
{
//create an object
$this->dbconn = new DBConnection();
//get user name from dbconnection class
echo $this->dbconn->username;
}
function User(){
}
}
//create object for user class
$user = new User();
**DBConnection class**
class DBConnection
{
public $SITEURL;
public $servername;
public $username;
public $password;
public $dbname;
public $objDbConnect;
function DBConnection(){
$this->SITEURL=Configuration::SITEURL;
$this->servername=Configuration::servername;
$this->username=Configuration::username;
$this->password=Configuration::password;
$this->objDbConnect=mysql_connect($this->servername,$this->username,$this->password);
if($this->objDbConnect){
mysql_select_db($this->dbname);
}
}
public static function getConnection(){
if(!empty($this)){
return $this;
}
return new DBConnection();
}
function InsertRecord($pStrTableName,$pArrField,$pArrValue)
{
$strSql="insert into $pStrTableName (";
$intFieldSize=count($pArrField);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.=$pArrField[$i];
}
else
{
$strSql.=$pArrField[$i].",";
}
}
$strSql.=") values (";
$intFieldSize=count($pArrValue);
for($i=0;$i<$intFieldSize;$i++)
{
if($i==$intFieldSize-1)
{
$strSql.="'".$pArrValue[$i]."'";
}
else
{
$strSql.="'".$pArrValue[$i]."'".",";
}
}
$strSql.=")";
if(mysql_query($strSql))
{
return 1;
}
else
{
return 0;
}
}
}
**Users class**
class Users{
var $username,
$userpassword,
$email,
function User(){
$db = DBConnection::getConnection();
$db->InsertRecord($x, $x, $x);
}
}
1 . You can change your class DBConnection to singleton. And call your class in User like this DBConnection::getInstance()->InsertRecord(...). It's easy. But not recommended.
2 . You can push your DBConnection instance inside User. Like this
class Users{
var $db_connection;
function __construct($db_connection){
$this->db_connection = $db_connection;
}
$db_connection = new DBConnection(...);
$user = new User($db_connection);
3 . You can instantiate new DBCOnnection inside User class. Like in #Sundar answer.
P.S. Do not use old construct style.
You can keep a reference to the DBConnection in your User class (pass it in in the constructor).
private $dbConn;
function __contruct($dbConnRef) {
$this->dbConn = $dbConnRef;
}
public function storeSelf() {
$this->dbConn->InsertRecord(...);
}
I'm trying to pass a PDO connection object from one class to another. But I'm not being very successfull. And I only want to instanciate only one PDO object.
With the help from dqhendricks and awm I managed to get the following solution working:
class Factory {
function createUser($id = NULL) {
return new User(Conn::get_conn(), $id);
}
function createApplication($id = NULL) {
return new User(Conn::get_conn(), $id);
}
}
class Conn {
private static $conn = NULL;
private function __construct() {}
private static function init() {
$conf = self::config();
try {
self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass']);
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
public static function get_conn() {
if (!self::$conn) { self::init(); }
return self::$conn;
}
private static function config($cfg_file = 'sl.config') {
$config = parse_ini_file('/../'.$cfg_file);
$conf = array();
$conf['user'] = $config['db_user'];
$conf['pass'] = $config['db_password'];
$conf['dsn'] = 'mysql:dbname='.$config['db_name'].';host='.$config['db_host'];
return $conf;
}
}
In my UserDAO class, I can now do this:
class UserDAO {
private $db;
private $id;
function UserDAO (&$db, $id) {
$this->db = &$db;
$this->id = &$id;
}
public function getRows($sql)
{
$result = $this->db->query($sql);
$row = $result->fetch(PDO::FETCH_ASSOC);
return $row;
}
function getUsers($limit = 10) {
$sql ="SELECT * FROM sl_store LIMIT $limit";
return $this->getRows($sql);
}
}
//My User class
class User extends UserDAO implements iUser {}
// And to test it working:
$user1 = Factory::createUser('5');
$user2 = Factory::createApplication('7');
How about defining an abstract class which gives you the PDO object on request?
E.g.
abstract class Db {
private static $x = null;
private static function init() {
try {
self::$x = new PDO(...);
} catch (PDOException $e) {
...
}
}
public static function getX() {
if (!self::$x) self::init();
return self::$x;
}
}
no need to have your class create an instance of itself if all you want is an instance of a different object back. maybe make a static method in Conn to return an instance of a db connection.
class Conn {
// prevent new statement
private __construct() {}
public static return_pdo() {
blah
blah
blah
return $db;
}
public static config($file) {
do stuff
}
}
then call statically
$pdo = Conn::return_pdo();
It's because new Conn() returns $Conn object, not the value from $Conn->Conn() method.
Try this:
class Conn{
function Conn() {
$db = new PDO($conf['dsn'], $conf['user'], $conf['pass']);
}
function get_db() {
return $this->db;
}
}
class Factory {
function createUser($id = NULL) {
$new_conn = new Conn();
$db = $new_conn->get_db();
}
}