Book Image

Laravel 5 Essentials

By : Martin Bean
Book Image

Laravel 5 Essentials

By: Martin Bean

Overview of this book

Table of Contents (15 chapters)
Laravel 5 Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Laravel's main features and sources of inspiration


So, what do you get out of the box with Laravel 5? Let's take a look and see how the following features can help boost your productivity:

  • Modularity: Laravel was built on top of over 20 different libraries and is itself split into individual modules. Tightly integrated with Composer dependency manager, these components can be updated with ease.

  • 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).

  • Configuration management: More often than not, your application will be running in different environments, which means that the database or e-mail server credential's settings or the displaying of error messages will be different when your app is running on a local development server to when it is running on a production server. Laravel has a consistent approach to handle configuration settings, and different settings can be applied in different environments via the use of an .env file, containing settings unique for that environment.

  • 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.

  • Schema builder, migrations, and seeding: Also inspired by Rails, these features allow you to define your database schema in PHP code and keep track of any changes with the help of database migrations. A migration is a simple way of describing a schema change and how to revert to it. Seeding allows you to populate the selected tables of your database, for example, after running a migration.

  • Template engine: Partly inspired by the Razor template language in ASP.NET MVC, Laravel ships with Blade, a lightweight template language with which you can create hierarchical layouts with predefined blocks in which dynamic content is injected.

  • 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.

  • Authentication: Since user authentication is such a common feature in web applications, out of the box Laravel comes with a default implementation to register, authenticate, and even send password reminders to users.

  • 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.

  • Queues: Laravel integrates with several queue services, such as Amazon SQS, Beanstalkd, and IronMQ, to allow you to delay resource-intensive tasks, such as the e-mailing of a large number of users, and run them in the background, rather than keep the user waiting for the task to complete.

  • 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.

Expressiveness and simplicity

Something that is at the core of Laravel is its philosophy that code should be named simply and expressively. Consider the following code example:

<?php

Route::get('area/{area}', function($area) {
  if (51 == $area && ! Auth::check()) {
    return Redirect::guest('login');
  } else {
    return 'Welcome to Area '.$area;
  }
})->where('area, '[0-9]+');

Tip

Downloading the example code

You can download the example code files for all Packt Publishing books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

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.

  • 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.

Responsibilities, naming, and conventions

At the beginning of this chapter, we pointed out that one of the main issues with standard PHP applications was the lack of a clear separation of concerns; business logic becomes entangled with the presentation and data tier. Like many other frameworks that favor convention over configuration, Laravel gives you scaffolding with predefined places to put code in. To help you eliminate trivial decisions, it expects you to name your variables, methods, or database tables in certain ways, even though these are editable via configuration. It is, however, far less opinionated than a framework such as Ruby on Rails and in areas like routing, where there is often more than one way to solve a problem.

You might remember us mentioning that Laravel is a framework that is based on the MVC paradigm. Do not worry if you have not used this architectural pattern before; in a nutshell, this is what you need to know about MVC in order to be able to build your first Laravel applications:

  • Models: Models represent resources in your application. More often than not, they correspond to records in a data store, most commonly a database table. In this respect, you can think of models as representing entities in your application, be that a user, a news article, or an event, among others. In Laravel, models are classes that usually extend Eloquent's base Model class and are named in CamelCase (that is, NewsArticle). This will correspond to a database table with the same name, but in snake_case and plural (that is, news_articles). By default, Eloquent also expects a primary key named id, and will also look for—and automatically update—the created_at and updated_at columns. Models can also describe the relationships they have with other models. For example, a NewsArticle model might be associated with a User model, as a User model might be able to author a NewsArticle model. However, models can also refer to data from other data sources, such as an XML file, or the response from a web service or API.

  • Controllers or routes: Controllers, at their simplest, take a request, do something, and then send an appropriate response. Controllers are where the actual processing of data goes, whether that is retrieving data from a database, or handling a form submission, and saving data back to a database. Although you are not forced to adhere to any rules when it comes to creating controller classes in Laravel, it does offer you two sane approaches: RESTful controllers and resource controllers. A RESTful controller allows you to define your own actions and what HTTP methods they should respond to. Resource controllers are based around an entity and allow you to perform common operations on that entity, based on the HTTP method used. Another option is to bypass using controller classes altogether and instead write your logic in your routes, by way of anonymous functions.

  • Views or Templates: Views are responsible for displaying the response returned from a controller in a suitable format, usually as an HTML web page. They can be conveniently built by using the Blade template language or by simply using standard PHP. The file extension of the view, either .blade.php or simply .php, determines whether or not Laravel treats your view as a Blade template or not.

The following diagram illustrates the interactions between all the constituents applied in a typical web application:

Of course, it is possible to go against the MVC paradigm and the framework's conventions and write code as you wish, but this will often require more effort on the developer's part for no gain.

Helping you become a better developer

Laravel has become a standard-bearer for a new way of developing PHP applications through various design decisions and philosophies, such as the way in which it advocates developers to write framework-agnostic code and to rely on contracts (interfaces) rather than implementations are only a good thing. It has also built such a strong community that it is undoubtedly one of its strongest assets and a major contributing factor to its success; it is possible to get answers within minutes from other users via avenues such as forums, IRC, and social networking websites like Twitter.

However, if time has taught us anything, it is that frameworks come and go and it is hard to predict when Laravel will lose its steam and be supplanted by a better or more popular framework. Nonetheless, Laravel will not only make you more productive in the short term, but it also has the potential to make you a better developer in the long run. By using it to build web applications, you will indirectly become more familiar with the following concepts, all of which are highly transferable to any other programming language or framework. These include the MVC paradigm and Object-oriented programming (OOP) design patterns, the use of dependency managers, testing and dependency injection, and the power and limitations of ORMs and database migration.

It will also inspire you to write more expressive code with descriptive DocBlock comments that facilitate the generation of documentation, as well as the future maintenance of the application, irrespective of whether it is done by you or another developer.