Skip to content
This repository
Browse code

Stub for database gateway

  • Loading branch information...
commit d2de5b58f9dbe41f6f909ab8a37bcaa4bbf7d3ff 1 parent faef64d
Jeremy Bush authored

Showing 1 changed file with 84 additions and 0 deletions. Show diff stats Hide diff stats

  1. +84 0 classes/automodeler/gateway/database.php
84 classes/automodeler/gateway/database.php
... ... @@ -0,0 +1,84 @@
  1 +<?php
  2 +
  3 +class AutoModeler_Gateway_Database extends AutoModeler_DAO_Database
  4 +{
  5 + protected $_model_name;
  6 +
  7 + /**
  8 + * Loads a database result. Can be used to load a single item into this model
  9 + * or return a result set of many models. You can pass any query builder object
  10 + * into the first parameter to load the specific data you need. Common usage:
  11 + *
  12 + * @param Database_Query_Builder_Select $query an optional query builder object to load with
  13 + * @param integer $limit a number greater than one will return a data set
  14 + *
  15 + * @return AutoModeler_Model when loading one object
  16 + * @return Database_Result when loading multiple results
  17 + */
  18 + protected function _load(Database_Query_Builder_Select $query = NULL)
  19 + {
  20 + $model = new $this->_model_name;
  21 +
  22 + // Start
  23 + $model->state(AutoModeler_Model::STATE_LOADING);
  24 +
  25 + // Use a normal select query by default
  26 + if ($query == NULL)
  27 + {
  28 + $query = new Database_Query_Builder_Select;
  29 + $query->select_array(array_keys($model->as_array()));
  30 + }
  31 +
  32 + $query->from($this->_table_name);
  33 +
  34 + // If we are going to return a data set, we want objects back
  35 + // How do we do this without passing $limit now?
  36 + if ($limit != 1)
  37 + {
  38 + $query->as_object($this->_model_name);
  39 + }
  40 +
  41 + $data = $query->execute($this->_db);
  42 +
  43 + if ($data->count() > 1)
  44 + {
  45 + return $data;
  46 + }
  47 +
  48 + // Process the results with this model's logic
  49 + if ($data->count() AND $data = $data->current())
  50 + {
  51 + $this->process_load($model, $data);
  52 +
  53 + return $this->process_load_state($model);
  54 + }
  55 + }
  56 +
  57 + /**
  58 + * Processes a load() from a result
  59 + *
  60 + * @return null
  61 + */
  62 + protected function process_load(AutoModeler_Model $model, array $data)
  63 + {
  64 + $model->set_fields($data);
  65 + }
  66 +
  67 + /**
  68 + * Processes the object state before a load() finishes
  69 + *
  70 + * @param AutoModeler_Model $model the model to process
  71 + *
  72 + * @return AutoModeler_Model
  73 + */
  74 + protected function process_load_state(AutoModeler_Model $model)
  75 + {
  76 + if ($model->id)
  77 + {
  78 + $model->state(AutoModeler_Model::STATE_LOADED);
  79 + }
  80 +
  81 + return $model;
  82 + }
  83 +
  84 +}

0 comments on commit d2de5b5

Please sign in to comment.
Something went wrong with that request. Please try again.