rgb192
asked on
create code to create object and instantiate.
<?php
//database.php
require_once('config.php');
class DBConnection{
private function Database(){
$databaseName=$GLOBALS['configuration']['db'];
$serverName=$GLOBALS['configuration']['host'];
$databaseUser=$GLOBALS['configuration']['user'];
$databasePassword=$GLOBALS['configuration']['pass'];
$databasePort=$GLOBALS['configuration']['port'];
$this->connection=mysql_connect($serverName.":".$databasePort,$databaseUser,$databasePassword);
mysql_set_charset('latin',$this->connection);
if($this->connection){
if(!mysql_select_db($databaseName)){
throw new Exception('Cannot find: "'.$databaseName.'"');
}
}
else
{
throw new Exception('Cannot connect to the database.');
}
}
public static function Connect(){
static $database=null;
if(!isset($database)){
$database=new Database();
}
return $database->connection;
}
public static function Reader($query,$connection){
$cursor=mysql_query($query,$connection);
return $cursor;
}
public static function Read($cursor){
return mysql_fetch_assoc($cursor);
}
public static function NonQuery($query,$connection){
mysql_query($query,$connection);
$result=mysql_affected_rows($connection);
if($result==-1){
return false;
}
return $result;
}
public static function Query($query,$connection){
$result=mysql_query($query,$connection);
return mysql_num_rows($result);
}
public static function InsertOrUpdate($query,$connection){
$result=mysql_query($query,$connection);
return intval(mysql_insert_id($connection));
}
}
<?php
//menu model.php
require_once('database.php');
class MenuItem{
//constructor (not implemented)
public function __construct(){
//set undeclared property
}
public function __set($property,$value){
$this->$property=$value;
}
//get defined property
function __get($property){
if(isset($this->$property)){
return $this->$property;
}
}
}
abstract class Menu{
private $menuid;
private $parentid;
private $menuitemid;
private $menuname;
private $decription;
public function setMenuID($menuid){$this->menuid=$menuid;}
public function getMenuID(){return $this->menuid;}
public function setMenuItemID($menuitemid){$this->menuitemid=$menuitemid;}
public function getMenuName(){return $this->menuname;}
public function setDescription($description){$this->decription=$description;}
public function getDescription(){return $this->decription;}
function getAllMenuItems($menuid){
$connection=Database::connect();
$this->query="select mitm.*, mi.itemname, mi.description,
mi.price, mi.picture, mi.servingsize
from `menuitemtomenu`
as mitm left join `menuitem`
as mi on mitm.menuitemid = mi.menuitemid
where mitm.menuid=$menuid";
$menuitemList=Array();
$cursor=Database::Reader($this->query,$connection);
while($row=Database::Read($cursor)){
$menuitem=new MenuItem;
$menuitem->menuitemid=$row['menuitemid'];
$menuitem->itemname=$row['itemname'];
$menuitem->price=$row['price'];
$menuitem->servingsize=$row['servingsize'];
$menuitem->description=$row['description'];
$menuitemList[]=$menuitem;
}
return $menuitemList;
}
}
class MainMenu extends Menu{
static public $title="<b><font color=blue>Main Menu</font></b>";
const id=1;
static public function menutime(){
return time();
}
}
class DrinkMenu extends Menu{
static public $title="<b><font color=lightblue>Drink Menu</font></b>";
const id=2;
}
class LunchMenu extends Menu{
static public $title="<b><font color=green>Lunch Menu</font></b>";
const id=3;
}
class KidsMenu extends Menu{
static public $title="<b><font color=yellow>Kids Menu</font></b>";
const id=5;
}
class DessertMenu extends Menu{
static public $title="<b><font color=red>Dessert Menu</font></b>";
const id=6;
}
class AppetizerMenu extends Menu{
static public $title="<b><font color=purple>Appetizer Menu</font></b>";
const id=7;
}
interface AdjustPortion{
public function setDinnerPortion($itemobject);
}
interface AdjustPrice{
public function setDinnerPrices($itemobject);
public function setHappyHourDrinkPrices($itemobject);
}
final class HappyHourMenu extends DrinkMenu implements AdjustPrice{
static public $title="<b><font color=orange>Happy Hour Drink Menu</font></b>";
public function setHappyHourDrinkPrices($menuitemobject){
$adjusted_price=1;
$base_price=$menuitemObject->getPrice();
//make the dinner price 30% less than the normal price
$adjusted_price=($base_price*0.7);
return round($adjusted_price,2);
}
public function setDinnerPrices($menuitemobject){}
}
final class DinnerMenu extends LunchMenu implements AdjustPortion,AdjustPrice
{
static public $title="<b><font color=blue>Dinner Menu</font></b>";
//DinnerMenu inherits ID from LunchMenu
public function setDinnerPortion($menuitemServingSize){
$adjustment=1;
$adjusted_servingsize="";
$portion=explode(" ",$menuitemServingSize);
//Make the dinner portions 50% bigger than the lunch portion.
foreach($portion as $subportion){
if (is_numeric($subportion)){
$adjustment=$subportion*1.5;
$adjusted_servingsize=$adjusted_servingsize." ".round($adjustment,2);
}
else{
$adjusted_servingsize=$adjusted_servingsize." ".$subportion;
}
}
return $adjusted_servingsize;
}
public function setDinnerPrices($menuitemPrice){
$adjusted_price=1;
//make the dinner price 25% more than the lunch price
try{
if ($menuitemPrice != 0){
$adjusted_price=($menuitemPrice * 1.25);
return round($adjusted_price,2);
}
else{
throw new Exception('MenuItem Price is $0.0');
}
}
catch(Exception $e){
echo "Caught exception: ".$e->getMessage()."<br>";
}
}
//override the base method to user the adjust price interface
public function GetAllMenuItems($menuid){
$connection=Database::Connect();
$this->query="select mitm.*, mi.itemname, mi.description,
mi.price,mi.picture,mi.servingsize
from `menuitemtomenu`
as mitm left join `menuitem`
as mi on mitm.menuitemid=mi.menuitemid
where mitm.menuid=$menu";
try{
// note: recall that the throw new Exception(...) statement is already in the database class in database.php
$menuitemList=Array();
$cursor=Database::Reader($this->query,$connection);
while($row=Database::Read($cursor)){
$menuitem=new MenuItem;
$menuitem->menuitemid=$row['menuitemid'];
$menuitem->itemname=$row['itemname'];
$menuitem->price=self::setDinnerPrices($row['price']);
$menuitem->description=$row['description'];
$menuitem->servingsize=self::setDinnerPortion($row['servingsize']);
$menuitemList[]=$menuitem;
}
return $menuitemList;
}
catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "<br>";
}
}
public function setHappyHourDrinkPrices($menuitemObject){}
}
//DBMapper handles most of the communication between the model and the database
class DBMapper extends Menu{
public function Erase($menuitemid){
try{
$connection=Database::Connect();
$this->query="Delect mi.*, mitm.* from `menuitem` as mi
LEFT join `menuitemtomenu` as mitm on mitm.menuitemid=mi.menuitemid
where mi.menuitemid=$menuitemid";
$rows=Database::Query($this->query,$connection);
}
catch(Exception $e){
echo "Caught exception in erase method: ".$e->getMessage(),"<br>";
}
}
public function save($data){
try{
$connection=Database::Connect();
if((isset($data["menuid"])&&(isset($data["menuitemid"])))){
//if the record doesn't exist then we will insert it
$this->query="select `menuitemid`, `menuid`
from `menuitemtomenu`
where `menuitemid`= ".$data['menuitemid']."
and `menuid`=".$data['menuid']." LIMIT 1";
//note: recall that the throw new Exception(...) statment is already in the
//database class in database.php
$rows=Database::Query($this->query,$connection);
if($rows==0){
$this->query="insert into `menuitemtomenu` (`menuitemid`,`menuid`) values (
".$data['menuitemid'].",".$data['menuid'] . ")";
}
$insertId=Database::InsertOrUpdate($this->query,$connection);
}
else{
$menuitem=new MenuItem;
$menuitem->itemid=$data['menuitemid'];
$menuitem->itemname=$data['itemname'];
$menuitem->description=$data['description'];
$menuitem->servingsize=$data['servingsize'];
$menuitem->picture=$data['picture'];
$menuitem->price=$data['price'];
}
//check to see if the record already exists in the menuitem table
//if so we will update, if not we will insert it
$this->query="select `menuitemid` from `menuitem`
where `menuitemid`='" . $menuitem->itemid . "'LIMIT 1";
//note: recall that the throw new exception(...) statement is already in the
//database class in database.php
$rows=Database::Query($this->query,$connection);
if ($rows>0){
$this->query="update `menuitem` set
`itemname`='" . mysql_real_escape_string($menuitem->itemname) . "',
`description`='".mysql_real_escape_string($menitem->description) . "',
`servingsize`='".$menuitem->servingsize . "',
`picture`='".$menuitem->picture."',
`price`='".$menuitem->price."' where `menuitemid`='".$menuitem->itemid."'";
}
else{
$this->query="insert into `menuitem`
(`itemname`,`description`,`servingsize`,`picture`,`price`) values (
'".mysql_real_escape_string($menuitem->itemname)."',
'".mysql_real_escape_string($menuitem->description)."',
'".$menuitem->servingsize."',
'".$menuitem->picture."'
'".$menuitem->price."')";
}
$insertId=Database::InsertOrUpdate($this->query,$connection);
}
catch(Exception $e){
echo "Caught exception in the save method: ". $e->getMessage(),"<br>";
}
}
public function getMenuItemTable(){
$connection=Database::Connect();
$this->query="select menuitemid, itemname, description,
price,picture,sevingsize
from `menuitem`";
$menuitemList=Array();
$cursor=Database::REader($this->query,$connection);
while($row=Database::Read($cursor)){
$menuitem=new MenuItem;
$menuitem->menuitemid=$row['menuitemid'];
$menuitem->itemname=$row['itemname'];
$menuitem->price=$row['price'];
$menuitem->servingsize=$row['servingsize'];
$menuitem->description=$row['description'];
$menuitemList[]=$menuitem;
}
return $menuitemList;
}
}
from an oop php tutorial
I spent a long time typing this code, and then the chapter ended. Maybe this code is used in a future chapter.
Can you please create code to create object and instantiate.
Not sure where you got that tutorial, but this part is a big WTF?
With most tutorials of any quality, you will find a downloadable code library. This can save you a lot of typing.
//get defined property
function __get($property){
if(isset($this->$property)){
return $this->$property;
}
}
What if $this->$property is not set? Then what? The script should probably throw an exception or return FALSE or something!With most tutorials of any quality, you will find a downloadable code library. This can save you a lot of typing.
ASKER
marqusG
Fatal error: Class 'Database' not found in C:\wamp\www\oop-beg\ch6-4. php on line 38
Ray:
http://www.phpthis.com/
okay there are problems with the code because there is no libraries for this example
Fatal error: Class 'Database' not found in C:\wamp\www\oop-beg\ch6-4.
Ray:
http://www.phpthis.com/
okay there are problems with the code because there is no libraries for this example
That error is not for my code: it's simple creation and instatiation of an object :).
The problem is that the script doesn't find Database class because... it doesn't exist. You have a file called Database.php but erroneously the class is called DBConnection. I say 'erroneously' because it is a good practice to put each class in a single file with the same name and since that class not only establish a connection with the database but perform queries and returns result, it should be named 'Database' and its first function it should be named Init or something like this.
The problem is that the script doesn't find Database class because... it doesn't exist. You have a file called Database.php but erroneously the class is called DBConnection. I say 'erroneously' because it is a good practice to put each class in a single file with the same name and since that class not only establish a connection with the database but perform queries and returns result, it should be named 'Database' and its first function it should be named Init or something like this.
I'm sorry, but I see other problems.
First of all, it's an old class, say for Php less than 5.3.3, when the constructor could have the same name of the class itself. As Php 5.3.3 the constructor must be named __construct and this is better because if you rename the class you don't have to rename the constructor also; in addition, each child class can call simply parent::__construct() without knowing its father's name - this sounds strange, I know. This is not a real problem, but it should be better learn using the latest technologies. I suggested you in another question to install xampp which brings you to the present.
Anyway, the first method in your class is the contructor, which initializes connection data grabbing them from config file.
But the method Connetc returns $this->connection without $connection property be declared! So the first line of your Database.php file should be:
Cheers
First of all, it's an old class, say for Php less than 5.3.3, when the constructor could have the same name of the class itself. As Php 5.3.3 the constructor must be named __construct and this is better because if you rename the class you don't have to rename the constructor also; in addition, each child class can call simply parent::__construct() without knowing its father's name - this sounds strange, I know. This is not a real problem, but it should be better learn using the latest technologies. I suggested you in another question to install xampp which brings you to the present.
Anyway, the first method in your class is the contructor, which initializes connection data grabbing them from config file.
But the method Connetc returns $this->connection without $connection property be declared! So the first line of your Database.php file should be:
<?php
//database.php
require_once('config.php');
class Database{
public $connection;
private function Database(){
$databaseName=$GLOBALS['configuration']['db'];
$serverName=$GLOBALS['configuration']['host'];
$databaseUser=$GLOBALS['configuration']['user'];
....
Cheers
I never heard of phpthis.com, but have a look at line 11 of the first code snippet.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
$this->connection=mysql_connect($serverName.":".$databasePort,$databaseUser,$databasePassword);
That mysql function is a big red flag.https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
ASKER
Marqus: i can not find construct. Ray i have read your mysql article many times and now use mysqli, pdo. Php has allowed me to cheat and not learn oop. So is there anything else wrong with this php oop tutorial?
Let me explain.
Your first code snippets begin with this:
Class should be Database because this way is called below in the code ($database=new Database(); at line 26, for instance).
The function Database is the constructor. As Php 5.3.3, the constructor is no mre called with the class name but with the special name __construct(). I'm sorry, I know this can be a bit confusing, but it's the language evolution an we must follow it.
So you're following a tutorial based on a Php version older than Php 5.3.3: this is not a very bad thing but it can be confusing if it is not explicited.
So if you use the code in the snippet in comment ID 39709320 it should work.
Your first code snippets begin with this:
<?php
//database.php
require_once('config.php');
class DBConnection{
private function Database(){
Class should be Database because this way is called below in the code ($database=new Database(); at line 26, for instance).
The function Database is the constructor. As Php 5.3.3, the constructor is no mre called with the class name but with the special name __construct(). I'm sorry, I know this can be a bit confusing, but it's the language evolution an we must follow it.
So you're following a tutorial based on a Php version older than Php 5.3.3: this is not a very bad thing but it can be confusing if it is not explicited.
So if you use the code in the snippet in comment ID 39709320 it should work.
anything else wrong with this php oop tutorial?I don't know. The articles and books that I trust are laid out in this article.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I will be asking questions about
PHP-Advanced-and-Object-or iented-Pro gramming-V isual-Quic kPro-Guide
which Ray recommends.
Thanks.
PHP-Advanced-and-Object-or
which Ray recommends.
Thanks.
Open in new window