Question

I'm currently developing a little private project in order to get more acquainted with PHP and OOP in general. Basically, I am creating a little app that is able to create posts and tag them.

The classes are organised like this so far:

  • Post
    Represents a post in the database, and has functions such as editPost(), attachTag(), etc.

  • Tag
    Represents a tag in the database, and similarly, has functions such as editTag(), etc.

  • PostUtils
    This is like a management interface, it is used to create/delete new posts and tags, list them, etc.

Now, when I instantiate a new Post object, I do so by passing the post ID as its required argument. When I do that, I would like to be able to check first whether the ID is valid or not. So far I've been doing that by using a method in the PostUtils class (isValidID($id)), so that the controller can perform a check before the Post class is instantiated. However, I've been reading about the Tell, Don't Ask principle, and it seems to me that I should perform this check within the Post class itself instead.

Ideally, I would like the object to be instantiated only when a valid ID is passed. So my question is, what would be the best behaviour for the class when a non-valid ID is passed instead? Does this make sense at all? Or does my whole architecture need to be changed to start with?

Thank you very much for your time, it is really appreciated :)

Was it helpful?

Solution

<?php
public class Post
{
  private function __construct($id)
  {
    /* Private constructor... do your normal initialization here */
  }

  private static function isValidID($id)
  {
    if (/*... check if $id is valid ... */) {
      return true;
    }
    return false;
  }

  public static function create($id)
  {
    if (!self::isValidID($id)) {
      return NULL; // Or throw an exception
    }

    return new Post($id);
  }
}
?>

And then you would use it, like:

<?php
  $post = Post::create(1234);

  if (is_null($post)) {
    /* Invalid ID */
  }
?>

Or if you opted to throw an exception:

<?php
  try {
    $post = Post::create(1234);
  } catch (YourInvalidIDException $e) {
    /* Invalid ID */
  }
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top