TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 05-16-2008, 02:39 AM   #1 (permalink)
The Wanderer
 
Join Date: Dec 2007
Posts: 18
Thanks: 2
xperience is on a distinguished road
Default How to think OOP ?

PHP Code:
<?php

require 'libs/Smarty.class.php';
require 
'config/newsRoom.config';

$smarty = new Smarty;

$smarty->compile_check true;
$smarty->debugging false;

$dbc    mysqli_connect(HOSTUSERNAMEPASSWORDDATABASE);

/* Retrieve List of all news Articles */
$query  mysqli_query($dbc"SELECT * 
                                FROM " 
TABLE .
                                
" ORDER BY id DESC
                                LIMIT 10"
);
$result = array();
$i      0;

while (
$n mysqli_fetch_array($query)) {
    
$tmp = array(
                
'id'         => $n['id'],
                
'date'         => $n['date'],
                
'location'     => $n['location'],
                
'title'     => $n['title'],
                
'summary'     => $n['summary'],
                
'article'     => $n['article']);
                
$result[$i++] = $tmp;
}

if (
$_GET['article'] == NULL) {
    
$article     = (int)$_GET['article'];
    
$query        mysqli_query($dbc"SELECT * 
                                      FROM "
TABLE 
                                     
" ORDER BY id DESC
                                         LIMIT 1"
);
    
$article     = array();
    while (
$a mysqli_fetch_array($query)) {
        
$article['id']             = $a['id'];
        
$article['date']         = $a['date'];
        
$article['location']     = $a['location'];
        
$article['title']         = $a['title'];
        
$article['summary']     = $a['summary'];
        
$article['article']     = $a['article'];
    }
}else {
    
    
$article     = (int)$_GET['article'];
    
$query        mysqli_query($dbc"SELECT * 
                                      FROM "
TABLE 
                                     
" WHERE id = $article");
    
$article     = array();
    while (
$a mysqli_fetch_array($query)) {
        
$article['id']             = $a['id'];
        
$article['date']         = $a['date'];
        
$article['location']     = $a['location'];
        
$article['title']         = $a['title'];
        
$article['summary']     = $a['summary'];
        
$article['article']     = $a['article'];
    }
}                         
    
    
$smarty->assign('article'$article);            
                
$smarty->assign('news'$result); 

$smarty->display('newsroom.tpl');

?>
I want to take code like this and convert it in to class(es). How do I look at this and say hey this should be a class ? I'm so lost on the simple stuff in OOP that I cannot move on. No matter how much I read and attempt I feel it's wrong. That and I just cannot wrap my head around the idea of taking something like a similiar mysql query and throw it in to a class.

Also .. if anyone has any suggestions on how to better my code please let me know :D
xperience is offline  
Reply With Quote
Old 05-16-2008, 07:39 PM   #2 (permalink)
The Frequenter
Newcomer 
 
xenon's Avatar
 
Join Date: Dec 2007
Location: Bucharest, Romania
Posts: 438
Thanks: 3
xenon is on a distinguished road
Default

You're thinking the wrong way. Not everything should be a class. Why? Because not everything must be thought in terms of OOP. Why instantiate a class to define some constants when you can do that without a class? Or why instantiate another class to include and configure some libraries, when that's completely unnecessary? Unlike Java, in PHP you have a choice. Use it wisely, though. Group libraries in classes, and combine that with design patterns. This is called, in one word, MVC.

This is the problem with people new to classes. They think 'hey, I can build a class to do that, why use procedural code?'. That's the way I was thinking when I first discovered OOP, and took me some time to figure what to do and what not to do in an OOP-manner. Study, and implement.
__________________
I have optimistic thoughts, even though sometimes (if not always) life's a bitch.
xenon is offline  
Reply With Quote
The Following User Says Thank You to xenon For This Useful Post:
xperience (05-21-2008)
Old 05-17-2008, 06:00 AM   #3 (permalink)
The Frequenter
Zend Certified 
 
Join Date: Sep 2007
Location: Denmark
Posts: 352
Thanks: 8
Kalle is on a distinguished road
Default

Quote:
Originally Posted by xenon View Post
You're thinking the wrong way. Not everything should be a class. Why? Because not everything must be thought in terms of OOP. Why instantiate a class to define some constants when you can do that without a class? Or why instantiate another class to include and configure some libraries, when that's completely unnecessary? Unlike Java, in PHP you have a choice. Use it wisely, though. Group libraries in classes, and combine that with design patterns. This is called, in one word, MVC.

This is the problem with people new to classes. They think 'hey, I can build a class to do that, why use procedural code?'. That's the way I was thinking when I first discovered OOP, and took me some time to figure what to do and what not to do in an OOP-manner. Study, and implement.
I can only agree with you on that
__________________
Send a message via MSN to Kalle Send a message via Skype™ to Kalle
Kalle is offline  
Reply With Quote
Old 05-21-2008, 09:28 PM   #4 (permalink)
The Wanderer
 
Join Date: Dec 2007
Posts: 18
Thanks: 2
xperience is on a distinguished road
Default

Say you come from a language like Java, where everything is object oriented. If someone were to come from like Java do they just have to accept the fact that everything in PHP doesn't have to be object based or do they continue to write how they are use to ? If so, how do they go about it ? Is it in any shape, way or form to become associate with writing in an OOP manner ?
xperience is offline  
Reply With Quote
Old 05-21-2008, 10:21 PM   #5 (permalink)
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

Disclaimer: I've never written in Java, so this is completely a personal opinion.

I don't think you have to accept anything, especially when it comes to PHP. One of its strengths (that some claim to be its weakness from time to time) is the fact that you have so many options for various methods of performing the same action. OOP is still relatively new to PHP but it's getting stronger and better every release. The thing you have to do as a programmer, again in my opinion, is decide what works best for you, your project, and/or your client.

If you come from an OOP background, and you decide everything you do should be in OOP, and you can make it work, then all the power to you. Some times though procedural markup can perform the exact same tasks, in less code, and more efficiently (in regards to server load, compile time, etc). This is where you have to make the decision, do I really need OOP? I started using it for everything once I finally figured out the basics of it, and I loved it. It came to a point though where I realized I was making some tasks far more complicated than they needed to be, just because I was trying to do it entirely in OOP. Since then I've gone back over a lot of my old code and made it a combination of OOP and procedural markup that runs way faster, and is far more organized.
-m
delayedinsanity is offline  
Reply With Quote
Old 05-26-2008, 11:00 PM   #6 (permalink)
may
The Wanderer
 
may's Avatar
 
Join Date: May 2008
Location: Netherlands
Posts: 5
Thanks: 0
may is on a distinguished road
Default

Look at some frameworks that implement Model view controller (MVC) and understand that OOP is all about seperation of logical functions.

For instance these tasks could be implemented as objects / classes within a certain web application.

1. Talking to, handling requests, abstracting an database from the main code (controller)
2. Validating, checking user input and env vars.
3. Creating, updating, destroying, altering session information.

What i am trying to point out is that you can break up logical tasks in classes and initiate them in memory (instances) as object(s). This is what oop is all about. This also explains why there are some obvious no-no`s in OOP. Like accessing properties directly (defies abstraction). creating methods in an controller or model class that contain HTML output (views). These should be broken up in different classes that handle only that.

Simple example
PHP Code:
// Our 'model' //
class person{
     private 
$name;
     private 
$health;

     public function 
__construct(){
        
self::name 'phpfreak';
        
self::health 'oke';
     }

     public function 
setHealth($health){
        if(!empty(
$health)){
           
self::health $health;
        }else{
           throw new 
exception('A person should have its health defined!');
        }
     }

}

// Our health 'controller' //
class illness extends person{
    
     private 
$numberofIllnesses;

     public function 
__construct(){
          
parent::__construct();
          if(!isset(
self::numberofillnesses)){
              
self::numberofillnesses 0;
          }
     }

     public function 
giveIllness($Illness){
        if(!empty(
$illness)){
           
self::numberofillnesses++;
           
$this->setHealth($Illness);
        }else{
           throw new 
exception('Person should be sick, but seemed immune...';
        }
     }
}
// Our diagnosing Doctor (view) //
class doctor extends illness{
 
      public function 
__construct(){
          
parent::__construct();
      }

      
// This method should not be called here so we overload it//
      
public function setHealth();

      public function 
getHistory(){
        echo 
'Our records show that Mr '.$this->name.' has been ill '.$this->numberofIllnesses.' times.';
      }

      public function 
getDiagnose(){
        if(!
$this->Health 'oke'){
         echo 
'Mr '.$this->name.' We found that you are suffering from '.$this->Health;
        }else{
         echo 
'Mr '.$this->name.' You seem fine at the moment';
        }
      }
}

$mvc = new doctor();
$mvc->getDiagnose();
$mvc->getHistory();
$mvc->giveIllness('Herpis');
$mvc->getDiagnose(); 
Ow well just to give you an basic idea of an approach.

as for your question, yes considering MVC you can surely break up the controller part that is still written in conditional scripting and create a controller. But the main question should be whats the use if the whole site isnt based on this principal?

OOP is to make the code easier to read, easier to extend, easier to alter and maintain. Problem is that when the whole site or at least an whole logical task within that site isnt based on OOP it might just get harder to maintain the whole. For instance the template engine is a logical task written in OOP (smarty framework). So smarty and your templating engine will be easy to update. But what about the part you like to implement into an class?

Is it realy an logical task of the site? and if so, shouldnt you create a way for all the code to access and use instances of that object so you actually gain something by creating an class out of it? and so forth. Consider the pro`s and cons carefully. Because if the object model (if any) is faulty you might as well mis the whole purpose of OOP programming ;)

-Regards,
may is offline  
Reply With Quote
Old 05-30-2008, 12:00 AM   #7 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

PHP Code:
$mvc->giveIllness('The Clap'); 
::runs:: (couldn't help myself!)
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 10:56 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design