Laravel 5 Essentials - Sample Chapter
Laravel 5 Essentials - Sample Chapter
P U B L I S H I N G
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
$ 29.99 US
19.99 UK
Sa
m
Laravel 5 Essentials
Martin Bean
Laravel 5 Essentials
Laravel 5 Essentials
ee
Martin Bean
Laravel 5 Essentials
Application frameworks have grown in popularity over the past five years. There
has been a tremendous shift from handwriting all code to leveraging these powerful
frameworks with prebuilt components and features. However, with anything that comes
to be in fashion, there are now a lot of contending options, and each of them viable.
While CodeIgniter was one of the first frameworks to enjoy widespread popularity,
this popularity would come to be its undoing years later, as its large spread use and low
barrier to entry meant it couldn't take advantage of newer versions of PHP without losing
backwards compatibility, and potentially breaking lots of applications. This saw it then
be surpassed by faster-moving alternatives such as Symfony and even FuelPHP, which
was developed as a response to CodeIgniter's unwillingness to embrace change.
Enter: Laravel. Laravel joined the framework scene when there were already many
players. However, the developers of Laravel used this timing to their advantage, instead
creating a framework that avoided all of the problems and mistakes previous full stack
frameworks had made and building on top of the excellent Symfony components in order
to create a robust, component-based framework.
Instead of providing dozens of inflexible libraries, Laravel provides sensible, driverbased components that developers could use to build applications their own way, rather
than trying to mash everything into the layout the framework author defined. This led
to Laravel rising in popularity. It was also a fast-moving framework, and, by version 4,
had become the most starred framework on GitHub, a testament to its popularity.
This book will give you a tour of Laravel and its core features. We'll look at how
to manage multiple Laravel applications on the same machine and then we'll go ahead
and start building our own Laravel application from scratch through to completion.
Once we've got a basic application reading and writing data from a database, we'll take
a look at Eloquent, Laravel's ORM, which is what makes it easy to read and write from
a database and the more advanced features it offers. From there, we'll look at Artisan,
Laravel's command-line utility, and even how to define our own commands. We'll then
learn how to write automated tests for our application to make sure it keeps working
the way we want it to, even with future developments. Then, finally, we'll look at how
to build login and registration systems using Laravel's user authentication component.
By the end of the book, you'll have a complete Laravel application, as well as the tools
and knowledge of how to build your own Laravel-based applications unassisted, and
where to continue your learning of the framework.
An Introduction to Laravel
PHP frameworks aren't new, but one of the newest on the block is Laravel. Since
version 3, Laravel has exploded in popularity to become one of the most popular
and widely used PHP frameworks in a short span of time. At the time of writing, the
Laravel repository on GitHub has more stars than its more mature contemporaries
such as Symfony, CakePHP, CodeIgniter, and Yii. So what is it about Laravel that
makes it so popular?
In this chapter, we will cover the following topics:
We will look at its key features and how they have made Laravel an indispensable
tool for many web developers. We will compare writing PHP applications with
and without a framework, and see how using a framework can aid in writing more
robust and better-structured PHP applications. Then, we will take a closer look at the
anatomy of a Laravel application and the third-party packages that it leverages. After
reading this chapter, you will have the knowledge needed to get started and build
your first Laravel application.
[1]
An Introduction to Laravel
Chapter 1
[3]
An Introduction to Laravel
Embracing PHP
One way in which Laravel differs from its contemporaries is that it openly embraces
new features of PHP and in turn requires a fairly recent version (at least 5.4).
Previously, other frameworks would build support for older versions of PHP to
maintain backwards-compatibility for as long as possible. However, this approach
meant that those same frameworks couldn't take advantage of new features in the
newer versions of PHP, in turn, hampering the evolution of PHP. Using Laravel 5,
you will get to grips with some of the newer features of PHP. If you're new to PHP,
or coming back to the language after a while, then here's what you can expect to find:
Interfaces: Interfaces specify the methods that a class should provide when
that interface is implemented. Interfaces do not contain any implementation
details themselves, merely the methods (and the arguments those methods
should take). For instance, if a class implements Laravel's JsonableInterface
instance, then that class will also need to have a toJson() method. Within
Laravel, interfaces tend to be referred to as Contracts.
[4]
Chapter 1
Shorter array syntax: PHP 5.4 introduced the shorter array syntax. Instead of
writing array('primes' =>array(1,3,5,7)), it is now possible to use just
square brackets to denote an array, that is, ['primes'=>[1,3,5,7]]. You
might know syntax if you've used arrays in JavaScript.
Testability: Built from the ground up to ease testing, Laravel ships with several
helpers that let you visit routes from your tests, crawl the resulting HTML,
ensure that methods are called on certain classes, and even impersonate
authenticated users in order to make sure the right code is run at the right time.
Routing: Laravel gives you a lot of flexibility when you define the routes
of your application. For example, you could manually bind a simple
anonymous function to a route with an HTTP verb, such as GET, POST, PUT,
or DELETE. This feature is inspired by micro-frameworks, such as Sinatra
(Ruby) and Silex (PHP).
[5]
An Introduction to Laravel
Query builder and ORM: Laravel ships with a fluent query builder, which
lets you issue database queries with a PHP syntax, where you simply chain
methods instead of writing SQL. In addition to this, it provides you with an
Object Relational Mapper (ORM) and ActiveRecord implementation, called
Eloquent, which is similar to what you will find in Ruby on Rails, to help
you define interconnected models. Both the query builder and the ORM are
compatible with different databases, such as PostgreSQL, SQLite, MySQL,
and SQL Server.
E-mailing: With its Mail class, which wraps the popular SwiftMailer
library, Laravel makes it very easy to send an e-mail, even with rich content
and attachments from your application. Laravel also comes with drivers for
popular e-mail sending services such as SendGrid, Mailgun, and Mandrill.
Redis: This is an in-memory key-value store that has a reputation for being
extremely fast. If you give Laravel a Redis instance that it can connect to,
it can use it as a session and general purpose cache, and also give you the
possibility to interact with it directly.
Event and command bus: Although not new in version 5, Laravel has
brought a command bus to the forefront in which it's easy to dispatch events
(a class that represents something that's happened in your application),
handle commands (another class that represents something that should
happen in your application), and act upon these at different points in your
application's lifecycle.
[6]
Chapter 1
Even though we have not even touched Laravel or covered its routing functions yet,
you will probably have a rough idea of what this snippet of code does. Expressive
code is more readable for someone new to a project, and it is probably also easier for
you to learn and remember.
Prettifying PHP
Prettifying PHP as well as ensuring code in Laravel is named to effectively convey
its actions in plain English, the authors of Laravel have also gone on to apply these
principles to existing PHP language functions. A prime example is the Storage class,
which was created to make file manipulations:
More expressive: To find out when a file was last modified, use
Storage::lastModified($path) instead of filemtime(realpath($path)).
To delete a file, use Storage::delete($path) instead of unlink($path),
which is the plain old PHP equivalent.
More consistent: Some of the original file manipulation functions of PHP are
prefixed with file_, while others just start with file; some are abbreviated
and other are not. Using Laravel's wrappers, you no longer need to guess or
refer to PHP's documentation.
[7]
An Introduction to Laravel
More testable: Many of the original functions can be tricky to use in tests,
due to the exceptions they throw and also because they are more difficult
to mock.
More feature complete: This is achieved by adding functions that did not
exist before, such as File::copyDirectory($directory, $destination).
There are very rare instances where expressiveness is foregone in the favor of
brevity. This is the case for commonly-used shortcut functions, such as e(), that
escape HTML entities, or dd(), with which you can halt the execution of the script
and dump the contents of one or more variables.
[8]
Chapter 1
The following diagram illustrates the interactions between all the constituents
applied in a typical web application:
[9]
An Introduction to Laravel
#
#
#
#
[ 10 ]
Chapter 1
./app/Handlers/
./app/Handlers/Commands
./app/Handlers/Events
./app/Http/
./app/Http/Controllers/
./app/Http/Middleware/
./app/Http/Requests/
./app/Http/routes.php
./app/Providers
./app/Services
# Exception handlers
# Handlers for command classes
# Handlers for event classes
#
#
#
#
./bootstrap/
./config/
# Configuration files
./database/
./database/migrations/
./database/seeds/
./public/
./public/.htaccess
./public/index.php
./resources/
./resources/assets/
./resources/lang/
./resources/views/
./storage/
./storage/app/
./storage/framework/
./storage/logs/
./tests/
# Test cases
./vendor/
./.env.example
./artisan
./composer.json
./phpunit.xml
./server.php
An Introduction to Laravel
Like Laravel's source code, the naming of directories is also expressive, and it is
easy to guess what each directory is for. The app directory is where most of your
application's server-side code will reside, which has subdirectories both for how
your application could be accessed (Console and Http), as well as subdirectories for
organizing code that could be used in both scenarios (such as Events and Services).
We will explore the responsibilities of each directory further in the next chapters.
Exploring Laravel
In this chapter, we are only covering the general mechanisms of how Laravel works,
without looking at the detailed implementation examples. For the majority of
developers, who just want to get the job done, this is sufficient. Moreover, it is much
easier to delve into the source code of Laravel once you have already built a few
applications. Nevertheless, here are some answers to the questions that might crop
up when exceptions are thrown or when you navigate through the source code. In
doing so, you will come across some methods that are not documented in the official
guide, and you might even be inspired to write better code.
[ 12 ]
Chapter 1
When searching for a class definition, for example, Auth, in the source code
or the API, you might bump into Facade, which hardly contains any helpful
methods and only acts as a proxy to the real class. This is because almost
every dependency in Laravel is injected into the service container when it
is instantiated.
Most of the libraries that are included in the vendor/ directory contain
a README file, which details the functionality present in the library (for
example, vendor/nesbot/carbon/readme.md).
An Introduction to Laravel
Summary
In this chapter, we have introduced you to Laravel 5 and how it can help you to
write better, more structured applications while reducing the amount of boilerplate
code. We have also explained the concepts and PHP features used by Laravel, and
you should now be well equipped to get started and write your first application!
In the next chapter, you will learn how to set up an environment in which you can
develop Laravel applications and you will also be introduced to Composer for
managing dependencies.
[ 14 ]
www.PacktPub.com
Stay Connected: