Welcome Guest, Not a member yet? Register   Sign In
Automatic toString value for Datamapper objects
#1

[eluser]tazoony[/eluser]
Hi,

Another contribution. I really hope one of these will be helpful Smile

To develop UI faster, and to clean up my code, I needed to automatically find the ideal name of a Datamapper object. So I creation a method object_name() in my DataMapper_Extra class that extends DataMapper class.

I realized that, in general, the field used as "label" was "name", "title", "label",... There are some recurring field names. Then my method will check all fields and find wich one is more suitable.

Here the code :


Code:
private $toString = '';


function __toString()
{
  return $this->object_name();
}

/**
  * Deduct the fields to use as title field.
  * @name object_name
  * @param $object
  * @return String
  */
function object_name()
{
  $_probable_label_fields = array('name','title', 'label', 'login','email');
  
  
  if (empty($this->toString)) {
  
   if (property_exists($this, 'title_field') )
   {
    $this->toString = $this->{$this->title_field};
   }
   else
   {
    
    // Default toString value, unless we find one better
    $this->toString = parent::__toString();
    
    // Looking for a probable title field
    foreach ($_probable_label_fields as $_probable_label_field)
    {
     if (in_array($_probable_label_field, $this->fields))
     {
      $this->toString = $this->{$_probable_label_field};
      break;
     }
    }
    
   }
    
  }
  
  
  return $this->toString;
}


So, for example :
Code:
$company = new Company();
$company->name = "IBM inc.";

echo $company; // Will prints : IBM inc.


I'm open minded about any improvement idea.
Enjoy.

Joffrey




Theme © iAndrew 2016 - Forum software by © MyBB