Laravel Introduction

Laravel Introduction

In this post I will start a series of articles about the Laravel framework. Originally developed by Taylor Otwell, Laravel has attracted more and more developers. The framework was created using the latest features of PHP, in addition to being completely rewritten in version 4. We’ll see Composer, namespaces and the directory structure of the Laravel. For whom is a PHP developer for a long time and still haven’t worked with the Laravel, there may be some resistance, but the change is worth it. For beginners, it is a way to enter the world PHP writing clean and quality code.

Talking a little about the adoption of Laravel, here’s a Google Trends search. It serves as a basis for comparison between some frameworks (notice the growth of Laravel):

MVC Model

Let’s start with the basics. Laravel is a MVC framework – structured in the form of Model-View-Controller. This means that you will divide your application into three parts (basically):

  • Models: classes used to represent your database. They serve as a layer of interaction with the database, eliminating those strings full of SQL logic from your application.
  • Views: the part of the application that the user will see. Here you put the HTML codes that will be displayed. Once again, this eliminates those ugly echos in the middle of the HTML code.
  • Controllers: responsible for the business logic. They are classes that will process the user input and decide what to do with it.

Just before this list I wrote that those were the three parts “basically”. That’s because in practice you’ll want to reuse many things and some of them will make more sense if separated from you app’s logic. For this reason you’ll end up using 3rd-party libraries (Laravel himself is a library) or creating your own. The Laravel greatly facilitates this reuse, because it allows the use of Namespaces and Composer.

Namespaces

Various languages already had namespaces for quite some time, but in PHP it was only included in version 5.3. They facilitate the reuse of components because they allow the use of the same names in classes. For example, without namespaces it is not possible to create a class Email to handle the database table “email”, and another class Email to actually send emails.

With the use of namespaces it is possible to identify before each class which “group” this class is a part. In this way it is possible to create two classes with the same name, since they belong to different namespaces.

Examples

Let’s go to the code to see it in practice.

In the above file we have a “normal” definition of class – without namespace. If another definition like this (without namespace) is made in any other part of the code, we have an error PHP Fatal error: Cannot redeclare class Email.

We can view on the highlighted line the Smtp namespace declaration. Now we won’t have any more errors. If we run the script:

What message do you think will appear on the screen? It’s the message “Without namespace”. As we didn’t declare any namespace, PHP will instantiate the class in the global namespace – all code created without namespace declaration is “loaded” in the global namespace – as a global variable.

And now, you know what’s going to show up? It’s the message “With namespace!”. Simple and extremely practical.

PHP requires that the first thing to be declared in the file is the namespace. It’s not possible to declare another namespace in the middle of the code.

Relativity

PHP considers everything that comes right after the namespace declaration as part of what has been declared. That is, if we create the following code:

In this case the class from the smtp.php file it will be instantiated, even without using the namespace when assigning the variable. And if we need to use the class Email from the email.php file, how can we do it? Simple, use only a “\” when instantiating to tell PHP that we want to use the class in the global namespace.

As a homework is the question of what will happen in the following case:

Answer in the comments!

Composer

Composer Logo

Composer is not a  Laravel component, but I added it in this introduction because many PHP developers have never had the opportunity to use it. According to the definition found in the website:

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

That is, you define the necessary libraries in your project and Composer will automatically fetch these libraries. If any of these libraries need other libraries, Composer will also get those, until your application has everything it needs to work. By default these libraries are not installed globally, but copied to a directory (vendor).

To set the dependencies, you need to create a file in JSON format. I won’t go into too much detail now because we’ll see that in the next post about the Laravel installation. So, in a text file, in order to define the dependency of our project with Laravel, we would write as follows:

This content goes in a file called composer.json. It defines that we need Laravel, and we need the 4.2.* version. To perform the installation of the dependence, we should run:

This will start the Composer execution, and it will copy Laravel to the directory vendor. If in the future you need to change the dependencies, for example:

In this case we are requesting, in addition to Laravel, the picture library Intervention Image (for image manipulation). After modifying the file, simply execute the command:

Composer will automatically update the libraries we need.

File structure

To complete this introduction to Laravel, I want to show the file structure of the framework.

Laravel structure 1

App directory

The app directory is the most important and, for this reason, I will detail it some more.

Laravel structure 2

This is the directory where your application will reside, that is why it is so important. The three sub-directories you will work more are controllers, models, and views. I’ll explain in order all the subdirectories of this folder.

  • commands: this directory keeps the routines and processes that will be executed from the command line (using php artisan command: command_name), or by using a cronjob to run the commands.
  • config: contains your application’s settings, such as connection settings with the database, driver, email settings, etc.
  • controllers: here you’ll put the controllers responsible for the logic of your application.
  • database: this directory will keep your migrations and seeds (scripts to populate your database automatically).
  • lang: If you need more translations for your application, this will hold the language files.
  • models: the classes that represent your database go in this folder.
  • start: some definitions for your application to load global environment, locally or via artisan (command line).
  • storage: storage of sessions (using the file session driver), logs, cache, etc.
  • tests: directory to place your automated tests.
  • views: this directory will store all the views of your application.

The two files inside the directory app are filters.php and routes.php. Inside filter.php you can place filters that will run depending on the URL. For example a filter that checks if the user is logged in, otherwise route the user to the home page. Inside the routes.php file are the route settings of your application. The routes indicate which URL will trigger which action. Some examples:

In these examples we have a route for when the user accesses the root, which will return a view called ‘hello’. Then we have two routes used for when the user access the URL /about – one of them performed when a get and another when a post is made. The last route is used when the user access the URL /user, it will be forwarded to the controller UserController and getIndex method. If the user accesses /user/create, it will be forwarded to the controller UserController and the getCreate method. When you run a post, it will be postCreate. In the next tutorials I will speak more about routes.

Other directories

  • bootstrap: the first directory after the app is the bootstrap directory. In this directory have some important initiation files:
    • autoload.php: responsible for loading libraries automatically. Loads the contents of the vendor (which will be created by the Composer).
    • paths.php: definition of Laravel directories. If you want to change the default directories.
    • start.php: application startup, with the instantiation of the application itself. The definition of the hosts for the development environment is also in this file.
  • public: next we see the directory public. Your images, JavaScripts and CSSs go into this directory so that they are accessible in the browser.

artisan

Among the files that are in this directory, we have two that deserve to be mentioned. The first is the artisan, which is a very important feature of Laravel. It is an application capable of performing a number of tasks through the command line. For example, to create a migration simply run:

This will create a new file in the folder app/database/migrations, with the basic structure of the migration class. After you populate the file with the creation of your table or modification, you can execute (perform the migration) using:

composer.json

The other important file is the compser.json. Here is where you will set the dependencies of your application.

Vendor directory

Here we have no vendor directory because this folders from Github, so it’s not a real application, only a version control for you to use as a template for your own application. If we use Composer here, this will create a directory called additional vendor, as already explained in the session dedicated to Composer.

Conclusion

This first article on Laravel was just to introduce some concepts of the framework. The use of namespaces and Composer, put the Laravel among the most up to date frameworks. In the next article I will write about the Laravel installation, how to clone from GitHub and do the initial settings. If you have any questions or suggestions, leave a comment.

This post is part of the Laravel Development series.

Leave a Reply

Your email address will not be published. Required fields are marked *