Solved

create code to create object and instantiate.

Posted on 2013-12-10
12
364 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 30

Expert Comment

by:Marco Gasi
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
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
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
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 30

Expert Comment

by:Marco Gasi
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:rgb192
Comment Utility
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 30

Expert Comment

by:Marco Gasi
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
... 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 30

Accepted Solution

by:
Marco Gasi earned 250 total points
Comment Utility
@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
Comment Utility
I will be asking questions about
PHP-Advanced-and-Object-oriented-Programming-Visual-QuickPro-Guide
which Ray recommends.

Thanks.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
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 look for a specific file type in a local or remote server directory using PHP.

763 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now