Constructors in Ruby & PHP Classes
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
.
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:
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
end
def update(params)
# update the current user
currentUser.update(params)
# log that the user has been updated.
@logger.info("#{currentUser.email} updated their account.')
end
end
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 = Logger.new
controller = UsersController.new(logger)
# 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.
controller.update(params)
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.