Requiring Other Files in PHP & Ruby
Requiring other files is an organizational method. We could place all of our application’s code into one file and it would work just fine. However, for you and your coworker’s sanity, we often break our application into logical groups. In order to reference that other piece of code later, we require
it.
Now to clarify, we’re not going to talk about PHP’s Autoloading with Composer. That’s a whole different topic. What I’m going to show is simply requiring another PHP or Ruby file into another. Namespacing and autoloading will be covered in the Advanced section of the series.
Requiring Files in PHP
In the days before we had Composer and the PSR standards, you had to use the built in PHP require
statement to bring in other files.
If you’re new to PHP development especially in modern frameworks such as Symfony or Laravel, you may not see this very often.
First let’s create a Dog
class in the same folder as our Cat
class.
Note:* You will see me use the word ‘directory’ in the future. Technically speaking “directories” and “folders” are the same concept. Linux and Unix decided “directories” was a better word than “folders”. Since most web servers run some form of Linux, the web development world has largely adopted the term “directory” to mean “folder”. Thanks for bearing with me.
Say we want to add Dog
to our new Cat
class so they can play together (awww). Turns out it’s pretty simple, we just require
our dog.php
file inside of our cat.php
file:
Relative Files
PHP’s require
is context based. When you’re requiring a file, it will look in the current file’s directory for the one you specified.
Remember we put the cat.php
and the dog.php
in the same directory? Let’s create a new directory called ‘other_animals’ in the current directory. Now I’m going to show you this next example with some command line stuff.
If you’re new to the command line, this will show you 3 basic commands. But the end goal here is to create a new directory called other_animals
and to move our dog.php
into it.
First, in your command line run this command:
mkdir other_animals
Then do a quick command to list the files in our current directory:
ls
You should see something like this:
cat.php dog.php other_animals
Now let’s move our dog.php
into that fresh other_animals
directory:
mv dog.php other_animals
And let’s verify that dog.php
was moved into other_animals
:
ls other_animals/
Fun Fact: you don’t have to type out the full names of files or directories. You have built in autocompletion. Try typing a part of a file’s name and hitting your Tab key twice. For example: type ca
and hit your Tab key twice, you’ll see your Terminal autocomplete the rest of the name cat.php
. This is because cat.php
is in the current directory and the Terminal is smart enough to find it. The more you know!
Ok, so now we have cat.php
in the current directory, and we have dog.php
in other_animals/dog.php
. So if we try to run our cat.php
example, it will fail with a E_COMPILE_ERROR
. Which basically just means “Hey, you said I could find dog.php
in the current directory, but it’s not here”.
So we need to let PHP know where this new file is, let’s edit cat.php
:
As you can see, we prepended other_animals
in front of the filename dog.php
. This is because we’ve moved our dog.php
to the other_animals
directory.
PHP’s include Method
In addition there’s another method in PHP for including other PHP files, and it’s called include
. It’s used in the same exact way as require
; however it does not throw a fatal error and halt the execution of the program if the file doesn’t exist.
Just do yourself a favor and don’t use it. You’ll save yourself some headaches. Better yet use PSR-4 autoloading via Composer in your application.
Requiring Files in Ruby
Now, on the surface Ruby is very similar to PHP’s interpretation of requiring other files. In fact, it uses the same keyword require
.
In many way’s Ruby’s require
acts in the same way as PHP’s require
. It will look for the file in the current directory or in the path you provide it one.
Let’s create a Ruby version of our Dog
class real quick in the same directory as cat.rb
:
class Dog
def woof
puts 'woof'
end
end
Fantastic. Now let’s go back to our cat.rb
and bring in a Dog to the party.
require 'dog'
class Cat
def meow
puts 'meow'
end
end
momma = Cat.new
momma.meow
dog = Dog.new
dog.woof
=> 'meow'
=> 'woof'
You probably noticed that we didn’t add the .rb
at the end of the require 'dog'
. Again, Ruby will implictly look for dog.rb
. You can absolutely use require dog.rb
and get the same results. However, most Rubyists and people in general like really legible code that’s as close to the human language as possible.
A Deeper Dive into Requiring Other Files
Unlike PHP, Ruby’s require
just doesn’t look in the current directory or the path you give it.
To explain, I’m going to first show you the built in CSV library.
The CSV library is a module that’s built right into the Ruby language. You don’t need to install additional dependencies to use it. You can read and write CSV files right out of the box. Pretty neat.
However, that doesn’t mean it’s available globally in every Ruby script. Just like your own files, you’ll need to require
it into the file you want to use it for.
Let’s create a CSV with the Ruby CSV module:
require 'csv'
CSV.open("example.csv", "wb") do |csv|
csv << ["cereal", "rating"]
csv << ["Honey Bunches of Oats", 3]
csv << ["Kashi", 2]
csv << ["Cascade Farms", 4]
csv << ["That one Banana Cereal from Trader Joes", 5]
end
Notice we didn’t have to specify a path to the csv
module. It just magically kind of found it. Well to help demystify what’s going on here, Ruby’s require
not only looks for files, but it looks for libaries by name.
Where does it look for libraries besides the current directory? In this special variable called $LOAD_PATH
.
We’ll cover how libraries and gems are added to the $LOAD_PATH
later in the book, but for now you can view all of the libarires Ruby is aware of by running a simple command in your Terminal:
ruby -e 'puts $LOAD_PATH'
Later you’ll learn where gems are stored when you install them. But just know that require
can be used in an explict absolute path fashion if you wish:
require './cat.rb'
Or it can be used to load libraries that are not in the current directory but are available in the $LOAD_PATH
, also known as $:
.
Ruby has an Include Method Too
Yes Ruby has an include
method. But it’s not for joining files as you’re familiar with. It actually includes the public methods of a class.
This is closer to PHP’s Trait functionality, and we’ll cover it in the Advanced Object Oriented Programming section of the book.