Laravel: From Apprentice To Artisan

Similar documents
The Laravel Survival Guide

Laravel and AngularJS

5. Application Layer. Introduction

Kotlin for Android Developers

Git Workbook. Self-Study Guide to Git. Lorna Mitchell. This book is for sale at

Building Secure PHP Apps

Modern Online Radio with Liquidsoap

Kotlin for Android Developers

Designing with OpenSCAD

The Design Patterns Matrix From Analysis to Implementation

Building Mapping Apps for ios With Swift

Functional Reactive Programming on ios

The Data Access Layer:

Personal Health Assistant: Final Report Prepared by K. Morillo, J. Redway, and I. Smyrnow Version Date April 29, 2010 Personal Health Assistant

Learn Gulp. Jonathan Birkholz. This book is for sale at This version was published on

An Incredibly Brief Introduction to Relational Databases: Appendix B - Learning Rails

Programming for Kids

How to Configure Outlook 2016 to connect to Exchange 2010

Functional Programming in Ruby

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O

For Volunteers An Elvanto Guide

Adding content to your Blackboard 9.1 class

A Primer on Design Patterns

TOP DEVELOPERS MINDSET. All About the 5 Things You Don t Know.

The Little Mongo DB Schema Design Book

Teach Yourself Enterprise Architect in Ten Days

Table of Laplace Transforms

What is version control? (discuss) Who has used version control? Favorite VCS? Uses of version control (read)

Speed Up Windows by Disabling Startup Programs

Step Up 4: Contracts Vs Facades

Customize Your Environment

3 Continuous Integration 3. Automated system finding bugs is better than people

How to set up SQL Source Control The short guide for evaluators

The first thing we ll need is some numbers. I m going to use the set of times and drug concentration levels in a patient s bloodstream given below.

Mock Objects and the Mockito Testing Framework Carl Veazey CSCI Friday, March 23, 12

Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas

Online Presentment and Payment FAQ s

Service-Oriented Architecture

Copyright. For more information, please read the Disclosures and Disclaimers section at the end of this ebook. First PDF Edition, February 2013

Learning to Provide Modern Solutions

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Laravel

Taskbar: Working with Several Windows at Once

Signing For Development/Debug

2005, Cornell University

Using Tiny ebook Reader Online

CS3205 HCI IN SOFTWARE DEVELOPMENT INTRODUCTION TO PROTOTYPING. Tom Horton. * Material from: Floryan (UVa) Klemmer (UCSD, was at Stanford)

1: Introduction to Object (1)

(Refer Slide Time 6:48)

Agile Architecture. The Why, the What and the How

Web Application Design. Husni Husni.trunojoyo.ac.id

15-Minute Fix: A Step-by-Step Guide to Designing Beautiful Dashboards

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

Docker for Sysadmins: Linux Windows VMware

1. You re boring your audience

Divisibility Rules and Their Explanations

Leaflet Tips and Tricks

Cloud-Native Applications. Copyright 2017 Pivotal Software, Inc. All rights Reserved. Version 1.0

Reasons to NOT Use . for Urgent Messages. Steuart Snooks. CEO Solutions For Success

SPRING MVC: BEGINNER'S GUIDE BY AMUTHAN G DOWNLOAD EBOOK : SPRING MVC: BEGINNER'S GUIDE BY AMUTHAN G PDF

Web Host. Choosing a. for Your WordPress Site. What is web hosting, and why do you need it?

introduction to records in touchdevelop

Let me begin by introducing myself. I have been a Progress Application Partner since 1986 and for many years I was the architect and chief developer

Heuristic Evaluation of Covalence

Assignment III: Graphing Calculator

Using Accommodate. Information for SAS Students at UofG

Crash Course in Modernization. A whitepaper from mrc

Emergency safety apps: which one is right for me?

Generate Hot Freelance Writing Leads with This Simple Template

Page design and working with frames

ACN INDEPENDENT BUSINESS OWNER GUIDE TO CUSTOMER EXPERIENCE

Absolute L A TEX Beginner

Midterm Exam, October 24th, 2000 Tuesday, October 24th, Human-Computer Interaction IT 113, 2 credits First trimester, both modules 2000/2001

Mail Findings. Australia Post Consumer Survey. Research into consumer preferences of transactional communications

Math 25 and Maple 3 + 4;

Build Testable Client and Service Applications

Course 319 Supplementary Materials. Effective User Manuals

GETTING STARTED WITH SPRING FRAMEWORK, SECOND EDITION BY ASHISH SARIN, J SHARMA

BUILDING ANDROID APPS IN EASY STEPS: USING APP INVENTOR BY MIKE MCGRATH

Alfresco Voice Writing for the user interface

Creating a new form with check boxes, drop-down list boxes, and text box fill-ins. Customizing each of the three form fields.

Introduction to User Stories. CSCI 5828: Foundations of Software Engineering Lecture 05 09/09/2014

UBC Coaching Services Human Resources 1/11. UBC Coaching Services: Coaching Portal Manual

Migrating. and Contacts. from TCT Mail to Gmail. Sponsored by. Presented by. Kristi Robison

Stop Scope Creep. Double Your Profit & Remove The Stress of Selling Websites

Just Do This: Back Up!

Analyzing PDFs with Citavi 6

[Maria Jackson Hittle] Thanks, Michael. Since the RSR was implemented in 2009, HAB has been slowing shifting its focus from data submission to data

Getting started with simulating data in R: some helpful functions and how to use them Ariel Muldoon August 28, 2018

ORB Education Quality Teaching Resources

Model-View-Controller Patterns and Frameworks. MVC Context

SharePoint 2010 Site Owner s Manual by Yvonne M. Harryman

Preface. WELCOME to Filthy Rich Clients. This book is about building better, more. Organization

Mr G s Java Jive. #11: Formatting Numbers

Asynchronous OSGi: Promises for the masses. Tim Ward.

Section 2. Sending s

1 Interface Fundamentals

A practicalintroduction to embedded programming. Brian Plancher 10/17/2018

The great primary-key debate

AngularJS Cookbook. 70 Recipes for AngularJS 1.2. Sascha Brink. This book is for sale at

Interaction Design: Part II

Transcription:

Laravel: From Apprentice To Artisan Advanced Architecture With Laravel 4 Taylor Otwell This book is for sale at http://leanpub.com/laravel This version was published on 2013-09-04 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. 2013 Taylor Otwell

Contents Dependency Injection....................................... 1 The Problem........................................... 1 Build A Contract........................................ 2 Taking It Further........................................ 4 Too Much Java?......................................... 6

Dependency Injection The Problem The foundation of the Laravel framework is its powerful IoC container. To truly understand the framework, a strong grasp of the container is necessary. However, we should note that an IoC container is simply a convenience mechanism for achieving a software design pattern: dependency injection. A container is not necessary to perform dependency injection, it simply makes the task easier. First, let s explore why dependency injection is beneficial. Consider the following class and method: 1 class UserController extends BaseController { 2 3 public function getindex() 4 { 5 $users = User::all(); 6 7 return View::make('users.index', compact('users')); 8 } 9 10 } While this code is concise, we are unable to test it without hitting an actual database. In other words, the Eloquent ORM is tightly coupled to our controller. We have no way to use or test this controller without also using the entire Eloquent ORM, including hitting a live database. This code also violates a software design principle commonly called separation of concerns. Simply put: our controller knows too much. Controllers do not need to know where data comes from, but only how to access it. The controller doesn t need to know that the data is available in MySQL, but only that it is available somewhere. Separation Of Concerns Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class. So, it will be beneficial for us to decouple our web layer (controller) from our data access layer completely. This will allow us to migrate storage implementations easily, as well as make our code easier to test. Think of the web as just a transport layer into your real application.

Dependency Injection 2 Imagine that your application is like a monitor with a variety of cable ports. You can access the monitor s functionality via HDMI, VGA, or DVI. Think of the Internet as just a cable into your application. The bulk of a monitor s functionality is independent of the cable. The cable is just a transport mechanism just like HTTP is a transport mechanism for your application. So, we don t want to clutter up our transport mechanism (the controller) with application logic. This will allow any transport layer, such as an API or mobile application, to access our application logic. So, instead of coupling our controller to the Eloquent ORM, let s inject a repository class. Build A Contract First, we ll define an interface and a corresponding implementation: 1 interface UserRepositoryInterface { 2 3 public function all(); 4 5 } 6 7 class DbUserRepository implements UserRepositoryInterface { 8 9 public function all() 10 { 11 return User::all()->toArray(); 12 } 13 14 } Next, we ll inject an implementation of this interface into our controller: 1 class UserController extends BaseController { 2 3 public function construct(userrepositoryinterface $users) 4 { 5 $this->users = $users; 6 } 7 8 public function getindex() 9 { 10 $users = $this->users->all(); 11 12 return View::make('users.index', compact('users'));

Dependency Injection 3 13 } 14 15 } Now our controller is completely ignorant of where our user data is being stored. In this case, ignorance is bliss! Our data could be coming from MySQL, MongoDB, or Redis. Our controller doesn t know the difference, nor should it care. Just by making this small change, we can test our web layer independent of our data layer, as well as easily switch our storage implementation. Respect Boundaries Remember to respect responsibility boundaries. Controllers and routes serve as a mediator between HTTP and your application. When writing large applications, don t clutter them up with your domain logic. To solidify our understanding, let s write a quick test. First, we ll mock the repository and bind it to the application IoC container. Then, we ll ensure that the controller properly calls the repository:

Dependency Injection 4 1 public function testindexactionbindsusersfromrepository() 2 { 3 // Arrange... 4 $repository = Mockery::mock('UserRepositoryInterface'); 5 $repository->shouldreceive('all')->once()->andreturn(array('foo')); 6 App::instance('UserRepositoryInterface', $repository); 7 8 // Act... 9 $response = $this->action('get', 'UserController@getIndex'); 10 11 // Assert... 12 $this->assertresponseok(); 13 $this->assertviewhas('users', array('foo')); 14 } Are You Mocking Me In this example, we used the Mockery mocking library. This library provides a clean, expressive interface for mocking your classes. Mockery can be easily installed via Composer. Taking It Further Let s consider another example to solidify our understanding. Perhaps we want to notify customers of charges to their account. We ll define two interfaces, or contracts. These contracts will give us the flexibility to change out their implementations later. 1 interface BillerInterface { 2 public function bill(array $user, $amount); 3 } 4 5 interface BillingNotifierInterface { 6 public function notify(array $user, $amount); 7 } Next, we ll build an implementation of our BillerInterface contract:

Dependency Injection 5 1 class StripeBiller implements BillerInterface { 2 3 public function construct(billingnotifierinterface $notifier) 4 { 5 $this->notifier = $notifier; 6 } 7 8 public function bill(array $user, $amount) 9 { 10 // Bill the user via Stripe... 11 12 $this->notifier->notify($user, $amount); 13 } 14 15 } By separating the responsibilities of each class, we re now able to easily inject various notifier implementations into our billing class. For example, we could inject a SmsNotifier or an EmailNotifier. Our biller is no longer concerned with the implementation of notifying, but only the contract. As long as a class abides by its contract (interface), the biller will gladly accept it. Furthermore, not only do we get added flexibility, we can now test our biller in isolation from our notifiers by injecting a mock BillingNotifierInterface. Be The Interface While writing interfaces might seem to a lot of extra work, they can actually make your development more rapid. Use interfaces to mock and test the entire back-end of your application before writing a single line of implementation! So, how do we do dependency injection? It s simple: 1 $biller = new StripeBiller(new SmsNotifier); That s dependency injection. Instead of the biller being concerned with notifying users, we simply pass it a notifier. A change this simple can do amazing things for your applications. Your code immediately becomes more maintainable since class responsibilities are clearly delineated. Also, testability will skyrocket as you can easily inject mock dependencies to isolate the code under test. But what about IoC containers? Aren t they necessary to do dependency injection? Absolutely not! As we ll see in the following chapters, containers make dependency injection easier to manage, but they are not a requirement. By following the principles in this chapter, you can practice dependency injection in any of your projects, regardless of whether a container is available to you.

Dependency Injection 6 Too Much Java? A common criticism of use of interfaces in PHP is that it makes your code too much like Java. What people mean is that it makes the code very verbose. You must define an interface and an implementation, which leads to a few extra key-strokes. For small, simple applications, this criticism is probably valid. Interfaces are often unnecessary in these applications, and it is OK to just couple yourself to an implementation you know won t change. There is no need to use interfaces if you are certain your implementation will not change. Architecture astronauts will tell you that you can never be certain. But, let s face it, sometimes you are. Interfaces are very helpful in large applications, and the extra key-strokes pale in comparison to the flexibility and testability you will gain. The ability to quickly swap implementations of a contract will wow your manager, and allow you to write code that easily adapts to change. So, in conclusion, keep in mind that this book presents a very pure architecture. If you need to scale it back for a small application, don t feel guilty. Remember, we re all trying to code happy. If you re not enjoying what you re doing or you are programming out of guilt, step back and re-evaluate.