Solved

create code to create object and instantiate.

Posted on 2013-12-10
12
387 Views
Last Modified: 2013-12-17
<?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));
  }
}

Open in new window






<?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;
}



}

Open in new window


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.
0
Comment
Question by:rgb192
  • 5
  • 4
  • 3
12 Comments
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39708611
The following lines create a menu of type Drink which extends abstract class Menu. Then, it get all menu items passing the correct id for drinks, that is 2, and echoes them.

$myMenu = new DrinkMenu();

$myMenuItems = $myMenu->getAllMenuItems(2);

foreach ($myMenuItems as $item) {
    echo $item . "<br />";
}

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39709154
Not sure where you got that tutorial, but this part is a big WTF?
  //get defined property
  function __get($property){
    if(isset($this->$property)){
      return $this->$property;
    }
  }

Open in new window

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.
0
 

Author Comment

by:rgb192
ID: 39709208
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
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39709255
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.
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39709320
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:

<?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'];

    ....

Open in new window


Cheers
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39709363
I never heard of phpthis.com, but have a look at line 11 of the first code snippet.
$this->connection=mysql_connect($serverName.":".$databasePort,$databaseUser,$databasePassword);

Open in new window

That mysql function is a big red flag.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
0
 

Author Comment

by:rgb192
ID: 39712408
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?
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 39712545
Let me explain.
Your first code snippets begin with this:

<?php
//database.php
require_once('config.php');
class DBConnection{
  private function Database(){

Open in new window


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.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39712680
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.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html
0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39712689
... The function Database is the constructor
That could only be true if this was a PHP4 script and the class name is Database.  It looks to me like the class name is DBConnection, not Database.

There is no rule about the placement of methods within the class.  The constructor does not need to be first, but it usually makes sense to put it first, along with any other magic methods.
0
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 250 total points
ID: 39713289
@Ray I think there is some error or in the tutorial book or some typo made during typing. Anyway, looking at the code posted, I thought the real class name was Database and a it was missing  the public property $connection. See the lines from 26 to 29 of the first snippet posted by rgb:

    $database=new Database(); //this would not make sense if the class name be DBConnection
    }
    return $database->connection; //and this shows the miised property
  }

Open in new window


I don't know who made these errors, but I'm sure these are errors and i think you can agree qith me about this.
The position of the constructor is not in my mind: I simply see the content of that function that is a prerequisite for the rest of code works - if it can work... :)
0
 

Author Closing Comment

by:rgb192
ID: 39725127
I will be asking questions about
PHP-Advanced-and-Object-oriented-Programming-Visual-QuickPro-Guide
which Ray recommends.

Thanks.
0

Featured Post

ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to dynamically set the form action using jQuery.

778 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question