20 May 2009 ~ 0 Comments

Quick and Easy Way to Create Model Class in PHP

Ever experienced a boring and time-consuming task where you have to create a new class for your model object: declaring list of variables and creating the getter and setter functions? “Always” is my answer. Imagine if you have a long list of variables. “Shoot! NOT AGAIN” may be the first exclamation came out from you. And for the sake of a good software design, the creation of these functions is essential. Blessed if you have excellent IDE to generate these for you.

So far I’ve been working with some IDEs out there like Microsoft Visual Studio (including Express edition), Eclipse for PHP, Zend Studio, and PHP Designer, and to me Visual Studio is the most developer-friendly IDE. But this task is still repetitive to me and personally I am into the notion of DRY (Don’t Repeat Yourself).

Well, I finally found a way to resolve this in PHP and I’m going to share this. The code is extended based on a sample file from Zend QuickStart.

/**
 * This class is a helper class that allows developer to
 * create an object model easily by simply inheriting and
 * declaring their desired variables as public in the child class
 * and seamlessly creates a pair of getter and setter functions.
 */
class JLoe_Model_Object
{
  /**
   * The regular expression for get method name.
   *
   * @var string
   */
  const REGEX_GET = '/get.*/';

  /**
   * The regular expression for set method name.
   *
   * @var string
   */
  const REGEX_SET = '/set.*/';

  /**
   * Get the value of a property with method syntax.
   *
   * Map method calls to get and set the declared public variables.
   * This is used to help to create magic get and set functions seamlessly.
   *
   * @param  string $method method name
   * @param  mixed  $param  parameter values to be passed
   * @return property value or this object
   */
  public function __call( $method, $param )
  {
    // Check whether it's a get or set method, else throw exception
    if ( preg_match( self::REGEX_GET, $method ) ) {
      $isGet = true;
      $propName = str_replace( 'get', '', $method );
    }
    elseif ( preg_match( self::REGEX_SET, $method ) ) {
      $isGet = false;
      $propName = str_replace( 'set', '', $method );
    }
    else { throw new JLoe_Model_Exception( 'Invalid method' ); }

    // Check whether property name exists
    $propName = ucfirst( $propName );
    if ( ! property_exists( $this, $propName ) ) {
      throw new JLoe_Model_Exception( 'Invalid method' );
    }

    // Perform respective method call
    if ( $isGet ) { return $this->$propName; }
    else
    {
      $this->$propName = $param[0];
      return $this;
    }
  }

  /**
   * Map variable access onto the underlying method representation.
   *
   * Allow to map the variable access with the respective get method.
   *
   * @param  string $name the property name to access
   * @return mixed value depending on the underlying method called
   */
  public function __get( $name )
  {
    $method = 'get' . $name;
    if ( ('mapper' == $name) || !method_exists($this, $method) )
    {
      throw new JLoe_Model_Exception( 'Invalid property' );
    }
    return $this->$method();
  }

  /**
   * Map variable access onto the underlying method representation.
   *
   * Allow to map the variable access with the respective set method.
   *
   * @param  string $name the property name to access
   * @return instance of the inherited class
   */
  public function __set( $name, $value )
  {
    $method = 'set' . $name;
    if ( ('mapper' == $name) || !method_exists($this, $method) )
    {
      throw new JLoe_Model_Exception( 'Invalid property' );
    }
    $this->$method( $value );
  }
}

And with this, you can code your model class with just a few lines. Here goes a sample.

class Quot_Model_Quote extends JLoe_Model_Object
{
  /**
   * Quote id.
   *
   * @var int
   */
  public $Id;

  /**
   * The quote
   *
   * @var string
   */
  public $Quote;

  /**
   * Tags for this quote.
   *
   * @var array
   */
  protected $_tags;
  public function getTags() { return $this->_tags; }
  public function setTags( $tags )
  {
    // Put your own logic here
    $this->_tags = $tags;
  }
}

Here if you wish to allow other class to access it via its variable name, getter, or setter functions, you just need to declare the variable as public as depicted on line 8 and 15. On the other hand, if you wish to limit access to a variable, you can always declare the variable as protected and create your desired getter or setter functions associated with the variable as shown on line 22 to 27.

And now you may access the class as follows.

$quote = new JLoe_Model_Quote();

$quote->Id   = $id;
$quote->Name = $name;
$quote->Tags = $tags;
// You may also use this
$quote
  ->setId( $id )
  ->setName( $name )
  ->setTags( $tags )

$id   = $quote->Id;
$name = $quote->Name;
$tags = $quote->tags;
// Similar with
$id   = $quote->getId();
$name = $quote->getName();
$tags = $quote->getTags();

It’s that easy. Now I can write my model class quickly and easily for other PHP projects. Yey! :)

If you find this post helpful, appreciate if you could leave your rating below to indicate that this post is really useful and at the same time let others know about this post. Thank you friend :)

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

Don't leave just yet! You may also be interested to take a quick look at my other posts.

  1. Start SOAP with Zend Framework
  2. Start ORM with LINQ in .Net Framework
  3. Zend Caveats
  4. Read Remote Content or File using Zend
  5. Image Manipulation in PHP

Leave a Reply

Spam protection by WP Captcha-Free