Constructors are an integral part to OOP programming. Constructors are the “magic method” that is called during Object instantiation.

If your class has dependencies on certain pieces of data, or even other objects - then the constructor is where to define those dependencies.

For simplicity, I’m going to assume the current user is accesible through a property like $this->currentUser.

class UsersController extends Controller {
   * @param Logger
   private $logger;

   * Constructor
   * @param Logger $logger 
   * @return void
  public function __construct(Logger $logger) {
    $this->logger = $logger;

   * Update user information
   * @param $request
   * @return Response
  public function update($params)
    // update the current user.

    // log that the user has been updated.
    $this->logger->info(sprintf('%s updated their account.', $this->currentUser->email));

Now, because we included the Logger as a dependency in the constructor of the UsersController, it’s saying we absolutely need the Logger in order to do work.

Because we depend on the Logger in the update method. It’s a good bet to place it as a constructor depedency.

So in the framework’s code you’ll see something like this when the request comes into to be fulfilled:

$logger = new Logger;

$controller = new UsersController($logger);


Now, there’s a lot more going on in real frameworks like Laravel. I’m not including things like route detection, constructor inference and fulfillment.

Example of a Ruby Constructor

Let’s create the same pseudo-UsersController in Ruby:

class UsersController < Controller {
  def initialize(logger)
    @logger = logger

  def update(params)
    # update the current user

    # log that the user has been updated."#{} updated their account.')

Notice that the initialize method is the Ruby equivalent of __construct. No fancy underscores required.

Under the hood, this fictional framework would do something like this to fulfill the user’s update request:

  logger =

  controller =

  # There isn't a super global variable like $_POST in Ruby.
  # I'll show how Ruby passes request & server information in "Hosting Ruby Web Applications" section.

Sure, PHP’s __construct “magic method” has a different name than Ruby’s reserved initialize method. But they both accomplish the same goal - enforce that an object has it’s dependencies fulfilled on instantiation.