da1lbi3
da1lbi3

Reputation: 4519

SQL Data mapping to objects

I want to create a backend that retrieves some information and maps it back to objects.

For example: I have this in my model class:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Core_Product_Model extends CI_model {

    //get the part id from an partnumber
    public function getIdFromPartnumber($partnumber){
        $this->db->select("id");
        $this->db->from('part_list');
        $this->db->where('part_number', $partnumber);
        $query = $this->db->get();

        return $query->result_object();
    }
}

And I handle it in my controller:

class Core_Product_Controller extends MX_Controller {
    public function getAllCrosslinks(){
            $response[] = array();
            $response['error'] = false;

            $partNumber = 100;

            $output = $this->Core_Product_Model->getIdFromPartnumber($partnumber);

            if(isset($output[0])){
                $response['output'] = $output;
                $response['valid'] = true;
            }

            echo json_encode($response);
        }
}

This works, but is not what I wanted. I want to retrieve everything as an object. This is not a problem to do, but is it a good design to do it that way?

Some Psuedo code:

Class Product:

class Product {
    private $productId;
    private $stock;

    function __construct($productId) {
        $this->productId = $productId;
    }

    function getProductId(){
        return $this->productId;
    }

    function stock(){

    }

    function setStock(Stock $stock){
        $this->stock = $stock;
    }

    function getStock(){
        return $this->stock;
    }
}

The model:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Core_Product_Model extends CI_model {

    //get the part id from an partnumber
    public function getIdFromPartnumber($partnumber){
        $this->db->select("*");
        $this->db->from('part_list');
        $this->db->where('part_number', $partnumber);
        $query = $this->db->get();

        $result = $query->result_object();

        //loop through result and map back to the Product class, save this to a array

        //return the array


        }
}

Is this a good approach to do it in this way?

Upvotes: 1

Views: 70

Answers (1)

Atural
Atural

Reputation: 5439

You've to do that in a model - since CI's Result Functions can provide this.

i'll show you a convenient way to do this (but you should know - this is only the beginning)

in your particular example you can do the following

class Core_Product_Model extends CI_model {

    //get the part id from an partnumber
    public function getIdFromPartnumber($partnumber){
        $this->db->select("id");
        $this->db->from('part_list');
        $this->db->where('part_number', $partnumber);
        $query = $this->db->get();

        return $query->result("Product");
    }
}

Be aware, due to naming conflicts (e.g. Product could be the name of a controller too) and the inability of CI to use namespaces you should name these Objects with a suffix (like Product_Object)

The next thing which comes to mind is, to use an autoloader as a hook because you dont want to use a "require" line for your objects in your models

simply put this class in to your application/hooks directory

class AppAutoLoadObjects 
{
    private $arrPaths = array(
        'objects/',
    );


    public function initialize()
    {
        spl_autoload_register(array($this,'autoloadObjects'));
    }

    public function autoloadObjects($class)
    {
        if (strpos($class, 'CI_') !== 0)
        {
            foreach ($this->arrPaths as $dir)
            {
                $this->counter++;
                if (file_exists(APPPATH . $dir . '/' . $class . '.php'))
                {
                    require_once(APPPATH . $dir . '/' . $class . '.php');
                    return;
                }
            }
        }
    }
}

and in the application/config/hooks.php

$hook['pre_system'] = [
    [
        'class' => 'AppAutoLoadObjects',
        'function' => 'initialize',
        'filename' => 'AppAutoLoadObjects.php',
        'filepath' => 'hooks'
    ]
];

Upvotes: 1

Related Questions