Search code examples
phpoopprocedural

Am I writing procedural code with objects or OOP?


So basically I'm making a leap from procedural coding to OOP. I'm trying to implement the principles of OOP but I have a nagging feeling I'm actually just writing procedural style with Objects.

So say I have a list of pipes/chairs/printers/whatever, they are all all listed as products in my single table database. I need to build a webapp that displays the whole list and items depending on their type, emphasis is on 'correct' use of OOP and its paradigm.

Is there anything wrong about just doing it like:

     CLass Show
     {

      public function showALL(){
      $prep = "SELECT * FROM myProducts";
      $q = $this->db-> prepare($prep);     
      $q->execute();
      while ($row = $q->fetch()) 
          {
            echo "bla bla bla some arranged display".$row['something']       
          }
      }

and then simply

$sth = new show();
$sth->showAll();

I would also implement more specific display methods like:

showSpecificProduct($id)->($id would be passed trough $_GET when user say clicks on one of the links and we would have seperate product.php file that would basically just contain

include('show.class.php');
$sth = new show();
$sth->showSpecificProduct($id);

showSpecificProduct() would be doing both select query and outputing html for display.

So to cut it short, am I going about it allright or I'm just doing procedural coding with classes and objects. Also any ideas/hints etc. on resolving it if I'm doing it wrong?


Solution

  • As well as the model practices described by @Phil and @Drew, I would urge you to separate your business, data and view layers.

    I've included a very simple version which will need to be expanded upon in your implementation, but the idea is to keep your Db selects separate from your output and almost "joining" the two together in the controller.

    class ProductController
    {
        public $view;
    
        public function __construct() {
            $this->view = new View;
        }
    
        public function indexAction() {
            $model = new DbProductRepository;
            $products = $model->fetchAll();
    
            $this->view->products = $products;
            $this->view->render('index', 'product');
        }
    }
    
    class View
    {
        protected $_variables = array();        
    
        public function __get($name) {
            return isset($this->_variables['get']) ? $this->_variables['get'] : null;
        }
    
        public function __set($name, $value) {
            $this->_variables[$name] = $value;
        }
    
        public function render($action, $controller) {
            require_once '/path/to/views/' . $controller . '/' . $action . '.php';
        }
    }
    
    // in /path/to/views/product/index.php
    foreach ($this->products as $product) {
        echo "Product ID {$product['id']} - {$product['name']} - {$product['cost']}<br />\n";
    }