At its core, encapsulation seeks to
  1. limit to the greatest extent practical the exposure of a class’ inner operations and properties
  2. group specific data with classes responsible for that data, and
  3. limit responsibility for distinct behaviors to particular classes as much as practical.
Function Encapsulation: Don’t Ask, Tell
  • Don’t ask: With a good Object Oriented architecture, you should simply not have to query an object’s state and then ask it to do something based on the results.
  • Tell: Instead, tell the class what to do and expect it to do its own status and sanity checks for you.
Bad Encapsulation

In this example of how not to do things, we will use the Nothing Public, getters/setters, paradigm

$userController = new UserController();

// Let's set the username and password...

// Make sure the user isn't logged in...
if (!$userController->isLoggedIn())
   // See if the username and password are right...
   if ($userController->validateLogin() === false)
      // Send them back to the login page.
      header('Location: /login.php');
      // They're legit, let's create their user session.
Good Encapsulation

In this example of good encapsulation, using the Real Property Encapsulation paradigm we won’t ask for anything at all.

$userController = new UserController();

// Let's attempt to login.
// We'll trust that UserController will do what is best for us and we
// will assume that we are done with the login process at this point as well.
$userController->login($user, $pass);

// Since an invalid user/pass would have redirected the user back to the login page,
// we can safely assume at this point that the user is logged in.
// However, just in case, we'll tell SecurityController to recheck and handle the situation
// appropriately if the user is, in fact, not logged in.
Examples of well-encapsulated classes
  • UserController
    • Private property $userManager (handles user actions)
    • No public properties
    • Behavior-specific public function register()
    • Behavior-specific public function login()
    • Behavior-specific public function editProfile()
  • No private properties.
  • No public properties.
  • Domain-specific public function isLoggedIn()
  • Behavior-specific public function ensureHasAccess()
  • Private property $userInfo (holds user info [name, etc.])
  • No public properties
  • Domain-specific public function createProfile()
  • Domain-specific public function updateProfile()
  • Domain-specific public function validateCredentials()