Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- How to handle an IF statement for every field in a table?
- Because every client I've used this code for over the years wanted to play fast and loose with the values in most DB fields I've had to allow all kinds of values in most fields. For example there are a number of fields where you'd assume you can only enter an integer. But most clients want to enter short phrases or whole paragraphs.
- So on many fields I have to test if the value is numeric or a string.
- Display strings as-is but run numbers through number_format and add a dollar sign.
- Some numbers just need to be run through number_format without the dollar sign.
- Or run it through a square foot to acre converter and add 'acres' or "sq ft" suffix.
- Or test if the value is a csv of strings and put a space between each comma.
- Or if it's a csv of id numbers pull the related records from the database.
- Or if it's a multi-line string convert it to an unordered list on some pages and a comma-space separated list on other pages.
- If the value is zero, don't show a zero.
- Some values are a zero or one and should be shown as yes or no.
- Some values are y or n and should be shown as yes or no.
- So what I've had to do is set up a bunch of IF statements for each field. The next problem was that there are many sections on the site where many of these fields would be displayed. So what I did next was to turn each field-specific IF statement into its own function. Later I grouped all those functions into a helper class.
- Below is that helper class and an example of its usage.
- Does this seem like a good idea? Is there a better way I could be handling this?
- */
- Usage:
- [code]
- <?
- $model = new ListingsModel(15671);
- $ldh = new ListingDisplayHelper( $model );
- $F = $ldh;
- ?>
- <tr><td>Property Name</td><td><?=$F->property_name?></td></tr>
- <tr><td>Categories</td><td><?=$F->category?></td></tr>
- <tr><td>Sale Price</td><td><?=$F->price?></td></tr>
- <tr><td>Rent Price</td><td><?=$F->rent_price?></td></tr>
- <tr><td>List Date</td><td><?=$F->list_date?></td></tr>
- <tr><td>Island</td><td><?=$F->island?></td></tr>
- <tr><td>Location</td><td><?=$F->location;?></td></tr>
- <tr><td>District</td><td><?=$F->district?></td></tr>
- <tr><td>Property Types</td><td><?=$F->property_types?></td></tr>
- <tr><td>Key Features</td><td><?=$F->key_features?></td></tr>
- <tr><td>Building_style</td><td><?=$F->building_style?></td></tr>
- <tr><td>Bedrooms</td><td><?=$F->bedrooms?></td></tr>
- <tr><td>Bathrooms</td><td><?=$F->bathrooms?></td></tr>
- <tr><td>Half Baths</td><td><?=$F->halfbaths?></td></tr>
- <tr><td>Lot Size</td><td><?=$F->lot_size?></td></tr>
- <tr><td>Living Area</td><td><?=$F->living_area?></td></tr>
- <tr><td>NRA</td><td><?=$F->net_rentable?></td></tr>
- <tr><td>GRA</td><td><?=$F->gross_rentable_area?></td></tr>
- <tr><td>Land Price/Sq.Ft.</td><td><?=$F->price_sq_ft?></td></tr>
- <tr><td>Building Rental Rate/Sq.Ft.</td><td><?=$F->sq_ft_rate?></td></tr>
- <tr><td>Total Expenses</td><td><?=$F->total_expenses?></td></tr>
- <tr><td>Vacancy Rate</td><td><?=$F->vacancy_rate?></td></tr>
- [/code]
- Helper Class:
- [code=php]
- ## This class should only be concerned with massaging
- ## the main listing values into preferred usable text values
- ## most useful in most common situations!
- ## ListingDisplayHelper requires a listing model object or stdclass or array of db record fields be passed into it.
- ## MAGIC METHODS:
- ### 1. Any property requested that exists on the root of the object itself is immediately returned.
- ### 2. The end result of any value tweaking methods is saved in ->cooked. So already cooked values are returned if found.
- ### 3. If a method matching the requested property is found that method cooks the raw value and caches it in ->cooked.
- ### It is also up to that method to decide what to do if the value is zero.
- ### 4. Any property requested that doesn't have an associated method will be pulled from ->raw.
- ###
- ### Any value that roughly equates to zero 0 will be converted to empty string.
- ### Things that don't actually exist in the db table will also go into ->cooked.
- class ListingDisplayHelper
- {
- public $_cooked; // adjusted values go in here
- public $_raw; // original values
- public $_log;
- public $_logging = false;
- // Some fields should never show zero even if that's their value.
- // But for debugging you can have them show another value (like - or !)
- // to make them easier to spot
- public $_zero_placeholder = '';
- function __construct( $listing )
- {
- $this->cooked = new stdclass;
- if( is_a( $listing, 'ListingsModel') )
- {
- $this->raw = (object) $listing->rowdata;
- $this->model = $listing;
- }
- elseif( is_array($listing) )
- {
- $this->raw = (object) $listing;
- }
- elseif( is_object($listing) )
- {
- $this->raw = $listing;
- }
- }
- # See MAGIC METHODS comment at top.
- public function __get($name)
- {
- if( false )
- { $nothing; }
- // check for top level class vars
- elseif( property_exists( $this, $name) )
- {
- $this->_log("found on obj `$name`");
- $to_return = $this->$name;
- }
- // check for vars that were already cooked (cached)
- elseif ( property_exists($this->cooked, $name) )
- {
- $this->_log("found in cooked `$name`" );
- $to_return = $this->cooked->$name;
- }
- // check for a matching method that would cook the vars value and cache it in ->cooked.
- elseif( method_exists($this, 'get_'.$name) )
- {
- $method = 'get_'.$name;
- $this->_log("method exists `$name`");
- $to_return = $this->$method( $name );
- }
- // check for the raw value
- elseif ( property_exists($this->raw, $name) )
- {
- $this->_log("found in raw `$name`" );
- $to_return = $this->raw->$name;
- }
- else {
- $this->_log("!!!!!! $name not found anywhere !!!!!!!");
- $to_return = "!!!!!! $name not found anywhere !!!!!!!";
- //$to_return = null;
- }
- if( (string) $to_return == '0' || $to_return == '0000-00-00' )
- { $to_return = $this->_zero_placeholder; }
- return $to_return;
- }
- private function _log($msg)
- {
- if($this->_logging) {
- $this->_log[] = $msg; }
- }
- public function get_island( $name )
- {
- return $this->cooked->island = $this->model->island();
- }
- public function get_location( $name )
- {
- return $this->cooked->location = $this->model->location();
- }
- public function get_district( $name )
- {
- return $this->cooked->district = $this->model->district();
- }
- public function get_property_types( $name )
- {
- $typeArray = $this->model->propertyTypes();
- return $this->cooked->property_types = implode(', ', $typeArray);
- }
- public function get_view_types( $name )
- {
- $typeArray = $this->model->viewTypes();
- return $this->cooked->view_types = implode(', ', $typeArray);
- }
- public function get_key_features( $name )
- {
- return $this->get_view_types ($name);
- }
- public function get_amenities( $name )
- {
- $typeArray = $this->model->amenities();
- return $this->cooked->amenities = implode(', ', $typeArray);
- }
- public function get_visible_on_site()
- {
- return $this->cooked->visible_on_site = ($this->raw->hide === 'no') ? 'yes' : 'no';
- }
- public function get_under_mls_control()
- {
- return $this->cooked->under_mls_control = ($this->raw->mls_imported === 'y') ? 'yes' : 'no';
- }
- function get_youtube_ids()
- {
- if(!empty( $this->raw->youtube_ids ))
- {
- $ytstring = $this->raw->youtube_ids;
- $ytstring = str_replace("\r\n", "\n", $ytstring);
- $ytstring = str_replace("\r", "\n", $ytstring);
- return $this->cooked->youtube_ids = $ytstring;
- }
- }
- function get_youtube_ids_array()
- {
- return $this->cooked->youtube_ids_array = explode("\n", $this->get_youtube_ids() );
- }
- function get_youtube_ids_linked()
- {
- $array = $this->get_youtube_ids_array();
- if(!empty($array))
- {
- $url = '<a href="https://www.youtube.com/watch?v=%s">%s</a>';
- foreach($array as $ytid)
- {
- $out[] = sprintf($url, $ytid, $ytid);
- }
- return $this->cooked->youtube_ids_linked = implode(', ', $out);
- }
- }
- // number of photos for this listing on local server
- public function get_local_photo_count()
- {
- $sql = "SELECT COUNT(*) AS `count` FROM media WHERE parent={$this->raw->listing_id} AND section='listings'
- AND (type='photo' OR type='cropA' OR type='cropB') GROUP BY parent";
- $result = sqlQuery($sql);
- if(!empty($result)) {
- return $this->cooked->local_photo_count = $result[0]['count']; }
- }
- public function get_category()
- {
- return $this->cooked->category = ucwords(str_replace(',' , ', ', $this->raw->category));
- }
- function get_price( $name )
- {
- return $this->get_sale_price( $name );
- }
- function get_sale_price( $name )
- {
- return $this->_cashmoney( $name );
- }
- function get_rent_price( $name )
- {
- return $this->_cashmoney( $name );
- }
- function get_land_price_sq_ft( $name )
- { return $this->get_price_sq_ft( $name ); }
- function get_price_sq_ft( $name )
- {
- return $this->_cashmoney( $name );
- }
- function get_building_sq_ft_rate( $name )
- {
- return $this->get_sq_ft_rate( $name );
- }
- function get_sq_ft_rate( $name )
- {
- return $this->_cashmoney( $name );
- }
- function get_total_expenses( $name )
- {
- return $this->_cashmoney( $name );
- }
- function get_vacancy_rate( $name )
- {
- return $this->_cashmoney( $name );
- }
- function get_goi( $name )
- {
- return $this->_numeric( $name );
- }
- function get_noi( $name )
- {
- return $this->_numeric( $name );
- }
- function get_insurance( $name )
- {
- return $this->_numeric( $name );
- }
- function get_assoc_fees( $name )
- {
- return $this->_numeric( $name );
- }
- function get_maint_fees( $name )
- {
- return $this->_numeric( $name );
- }
- function get_rent_deposit( $name )
- {
- return $this->_numeric( $name );
- }
- function get_security_deposit( $name )
- {
- return $this->_numeric( $name );
- }
- function get_phone_deposit( $name )
- {
- return $this->_numeric( $name );
- }
- function get_water_deposit( $name )
- {
- return $this->_numeric( $name );
- }
- function get_power_deposit( $name )
- {
- return $this->_numeric( 'bec_deposit' );
- }
- function get_bec_deposit( $name )
- {
- return $this->_numeric( $name );
- }
- /**
- * For things that are probably a number but might not be.
- * In the negative case return the original string.
- */
- private function _numeric( $name )
- {
- if(is_numeric($this->raw->$name)){ return $this->_cashmoney( $name ); }
- else { return $this->cooked->$name = $this->raw->$name; }
- }
- // Damned `RPTax` is the only camel cased table field.
- function get_rptax( $name )
- {
- $name = 'rptax'; // normalize the name
- $value = $this->raw->rptax = $this->raw->RPTax; // the lower case name needs to exist in raw for _cashmoney to work
- $this->cooked->$name = $value;
- if(is_numeric( $value )){ return $this->_cashmoney( $name ); }
- else { return $this->cooked->$name; }
- }
- function get_land_sq_ft()
- {
- return $this->get_lot_size();
- }
- function get_lot_size()
- {
- $size = $this->_sqftacre($this->raw->lot_size);
- $this->cooked->land_sq_ft = $size;
- $this->cooked->lot_size = $size;
- return $size;
- }
- function _sqftacre( $input )
- {
- if(empty($input)){ return ''; }
- $out = strtolower(sqftacre( $input ));
- $out = explode(' ', $out);
- if( $out[1] == 'acres' || $out[1] == 'acre'){ return implode(' ', $out); }
- else {return $out[0].' sq.ft.';}
- }
- function get_living_area()
- {
- return $this->_squarefeet('living_area');
- # Sizes of building internals should never be represented in acres.
- }
- function get_gross_building()
- {
- return $this->_squarefeet('gross_building');
- # Sizes of building internals should never be represented in acres.
- }
- function get_building_area()
- {
- return $this->get_gross_building();
- }
- function get_net_rentable()
- {
- return $this->_squarefeet('net_rentable');
- # Sizes of building internals should never be represented in acres.
- }
- function get_nra()
- {
- return $this->get_net_rentable();
- }
- function get_gross_rentable_area()
- {
- return $this->_squarefeet('gross_rentable_area');
- // anything building related should always be in square feet.
- }
- function get_gra()
- {
- return $this->get_gross_rentable_area();
- }
- private function _squarefeet( $var )
- {
- if( empty($this->raw->$var) ){ return ''; }
- return $this->cooked->$var = number_format($this->raw->$var).' sq.ft.';
- }
- // For when you're sure something is money and should show a $ and commas.
- // In the negative case show nothing.
- private function _cashmoney( $var )
- {
- if( 0 == (int) $this->raw->$var ) { $this->cooked->$var = ''; }
- else { $this->cooked->$var = '$'. number_format($this->raw->$var); }
- return $this->cooked->$var;
- }
- public function get_view_count()
- {
- $sql = "SELECT totalhits FROM listings_hits WHERE listing_id = {$this->raw->listing_id}";
- $count = sqlQuery($sql);
- if( !empty($count) ) { return $this->cooked->view_count = $count[0]['totalhits']; }
- }
- public function get_bedrooms()
- {
- if($this->raw->bedrooms == 0) { return $this->cooked->bedrooms = null; }
- else { return $this->cooked->bedrooms = $this->raw->bedrooms; }
- }
- public function get_bathrooms()
- {
- $bathrooms = (float) $this->raw->bathrooms;
- if($bathrooms == 0) { $bathrooms = null; }
- if(strpos($bathrooms, '.5') !== false)
- {
- $bathrooms = str_replace('.5', "½", $bathrooms);
- }
- elseif( (int)$this->raw->halfbaths > 0 && $bathrooms > 0)
- {
- $bathrooms .= "½";
- }
- return $this->cooked->bathrooms = $bathrooms;
- }
- }
- [/code]
Advertisement
Add Comment
Please, Sign In to add comment