TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Advanced PHP Programming (http://www.talkphp.com/advanced-php-programming/)
-   -   How to think OOP ? (http://www.talkphp.com/advanced-php-programming/2809-how-think-oop.html)

xperience 05-16-2008 02:39 AM

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

xenon 05-16-2008 07:39 PM

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.

Kalle 05-17-2008 06:00 AM

Quote:

Originally Posted by xenon (Post 14684)
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 8-)

xperience 05-21-2008 09:28 PM

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 ?

delayedinsanity 05-21-2008 10:21 PM

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

may 05-26-2008 11:00 PM

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,

drewbee 05-30-2008 12:00 AM

PHP Code:

$mvc->giveIllness('The Clap'); 

::runs:: (couldn't help myself!)


All times are GMT. The time now is 11:39 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0