logo资料库

Laravel Up and Running A Framework for Building Modern PHP Apps.pdf

第1页 / 共795页
第2页 / 共795页
第3页 / 共795页
第4页 / 共795页
第5页 / 共795页
第6页 / 共795页
第7页 / 共795页
第8页 / 共795页
资料共795页,剩余部分请下载后查看
Preface
What This Book Is About
Who This Book Is For
How This Book Is Structured
Conventions Used in This Book
O’Reilly Safari
How to Contact Us
Acknowledgments
1. Why Laravel?
Why Use a Framework?
“I’ll Just Build It Myself”
Consistency and Flexibility
A Short History of Web and PHP Frameworks
Ruby on Rails
The Influx of PHP Frameworks
The Good and the Bad of CodeIgniter
Laravel 1, 2, and 3
Laravel 4
Laravel 5
What’s So Special About Laravel?
The Philosophy of Laravel
How Laravel Achieves Developer Happiness
The Laravel Community
How It Works
Why Laravel?
2. Setting Up a Laravel Development Environment
System Requirements
Composer
Local Development Environments
Laravel Valet
Laravel Homestead
Setting up Homestead
Installing Homestead’s dependencies
Installing Homestead
Configuring Homestead
Creating databases in Homestead
Provisioning Homestead
Using Homestead day-to-day
Connecting to Homestead databases from desktop applications
Creating a New Laravel Project
Installing Laravel with the Laravel Installer Tool
Installing Laravel with Composer’s create-project Feature
Laravel’s Directory Structure
The Folders
The Loose Files
Configuration
Up and Running
Testing
TL;DR
3. Routing and Controllers
Route Definitions
Route Verbs
Route Handling
Route Parameters
Route Names
Route Groups
Middleware
Path Prefixes
Subdomain Routing
Namespace Prefixes
Name Prefixes
Views
Using View Composers to Share Variables with Every View
Controllers
Getting User Input
Injecting Dependencies into Controllers
Resource Controllers
The methods of Laravel’s resource controllers
Binding a resource controller
Route Model Binding
Implicit Route Model Binding
Custom Route Model Binding
Route Caching
Form Method Spoofing
An Introduction to HTTP Verbs
HTTP Verbs in Laravel
HTTP Method Spoofing in HTML Forms
CSRF Protection
Redirects
redirect()->to()
redirect()->route()
redirect()->back()
Other Redirect Methods
redirect()->with()
Aborting the Request
Custom Responses
response()->make()
response()->json() and ->jsonp()
response()->download() and ->file()
Testing
TL;DR
4. Blade Templating
Echoing Data
Control Structures
Conditionals
@if
@unless and @endunless
Loops
@for, @foreach, and @while
@forelse
or
Template Inheritance
Defining Sections with @section/@show and @yield
@extends
@section and @endsection
@parent
@include
@each
View Composers and Service Injection
Binding Data to Views Using View Composers
Sharing a variable globally
Closure-based view composers
Class-based view composers
Blade Service Injection
Custom Blade Directives
Parameters in Custom Blade Directives
Example: Using Custom Blade Directives for a Multitenant App
Testing
TL;DR
5. Frontend Components
Elixir
Elixir Folder Structure
Running Elixir
What Does Elixir Provide?
The --production flag
Passing multiple files
Source maps
Preprocessorless CSS
Concatenating JavaScript
Processing JavaScript
Versioning
Tests
Elixir extensions
Pagination
Paginating Database Results
Manually Creating Paginators
Message Bags
Named Error Bags
String Helpers, Pluralization, and Localization
The String Helpers and Pluralization
Localization
Basic localization
Parameters in localization
Pluralization in localization
Testing
Testing with Elixir
Testing Message and Error Bags
Translation and Localization
TL;DR
6. Collecting and Handling User Data
Injecting a Request Object
$request->all()
$request->except() and $request->only()
$request->has() and $request->exists()
$request->input()
Array Input
JSON Input (and $request->json())
Route Data
From Request
From Route Parameters
Uploaded Files
Validation
validate() in the Controller Using ValidatesRequests
Manual Validation
Displaying Validation Error Messages
Form Requests
Creating a Form Request
Using a Form Request
Eloquent Model Mass Assignment
{{ Versus {!!
Testing
TL;DR
7. Artisan and Tinker
An Introduction to Artisan
Basic Artisan Commands
Options
The Grouped Commands
Writing Custom Artisan Commands
Registering Commands
A Sample Command
Arguments and Options
Arguments, required, optional, and/or with defaults
Options, required values, value defaults, and shortcuts
Array arguments and array options
Input descriptions
Using Input
argument()
option()
Prompts
Output
Table output
Progress bars
Calling Artisan Commands in Normal Code
Tinker
Testing
TL;DR
8. Database and Eloquent
Configuration
Database Connections
Other Database Configuration Options
Migrations
Defining Migrations
Creating a migration
Creating tables
Creating columns
Building extra properties fluently
Dropping tables
Modifying columns
Indexes and foreign keys
Adding indexes
Removing indexes
Adding and removing foreign keys
Running Migrations
Seeding
Creating a Seeder
Model Factories
Creating a model factory
Using a model factory
Overriding properties when calling a model factory
Generating more than one instance with a model factory
Defining and accessing multiple model factory types
Query Builder
Basic Usage of the DB Facade
Raw SQL
Raw selects
Parameter bindings and named bindings
Raw inserts
Raw updates
Raw deletes
Chaining with the Query Builder
Constraining methods
Modifying methods
Ending/returning methods
Writing raw queries inside query builder methods with DB::raw
Joins
Unions
Inserts
Updates
Deletes
JSON operations
Transactions
Introduction to Eloquent
Creating and Defining Eloquent Models
Table name
Primary key
Timestamps
Retrieving Data with Eloquent
Get one
Get many
Chunking responses with chunk()
Aggregates
Inserts and Updates with Eloquent
Inserts
Updates
Mass assignment
firstOrCreate() and firstOrNew()
Deleting with Eloquent
Normal deletes
Soft deletes
Enabling soft deletes
Querying with soft deletes
Restoring soft-deleted entities
Force-deleting soft-deleted entities
Scopes
Local scopes
Global scopes
Removing global scopes
Customizing Field Interactions with Accessors, Mutators, and Attribute Casting
Accessors
Mutators
Attribute casting
Date mutators
Eloquent Collections
Introducing the base collection
What Eloquent collections add
Eloquent Serialization
Returning models directly from route methods
Hiding attributes from JSON
Eloquent Relationships
One to one
One to many
Using relationships as query builders
Selecting only records that have a related item
Has many through
Many to many
Getting data from the pivot table
Polymorphic
Many to many polymorphic
Child Records Updating Parent Record Timestamps
Eager loading
Constraining eager loads
Lazy eager loading
Eager loading only the count
Eloquent Events
Testing
TL;DR
9. User Authentication and Authorization
The User Model and Migration
Using the auth() Global Helper and the Auth Facade
The Auth Controllers
RegisterController
RegistersUsers trait
LoginController
AuthenticatesUsers trait
ThrottlesLogins trait
ResetPasswordController
ForgotPasswordController
Auth::routes()
The Auth Scaffold
“Remember Me”
Manually Authenticating Users
Auth Middleware
Guards
Changing the Default Guard
Using Other Guards Without Changing the Default
Adding a New Guard
Creating a Custom User Provider
Custom User Providers for Nonrelational Databases
Auth Events
Authorization (ACL) and Roles
Defining Authorization Rules
The Gate Facade (and Injecting Gate)
The Authorize Middleware
Controller Authorization
Checking on the User Instance
Blade Checks
Intercepting Checks
Policies
Generating policies
Checking policies
Overriding policies
Testing
TL;DR
10. Requests and Responses
Laravel’s Request Lifecycle
Bootstrapping the Application
Laravel’s kernel
Service Providers
The Request Object
Getting a Request Object in Laravel
Getting Basic Information About a Request
Basic user input
User and request state
Files
Persistence
The Response Object
Using and Creating Response Objects in Controllers
Setting headers
Adding cookies
Specialized Response Types
View responses
Download responses
File responses
JSON responses
Redirect responses
Custom response macros
Laravel and Middleware
An Introduction to Middleware
Creating Custom Middleware
Understanding middleware’s handle() method
Binding Middleware
Binding global middleware
Binding route middleware
Using middleware groups
Passing Parameters to Middleware
Testing
TL;DR
11. The Container
A Quick Introduction to Dependency Injection
Dependency Injection and Laravel
The app() Global Helper
How the Container Is Wired
Binding Classes to the Container
Binding to a Closure
Binding to Singletons, Aliases, and Instances
Binding a Concrete Instance to an Interface
Contextual Binding
Constructor Injection
Method Injection
Facades and the Container
How Facades Work
Service Providers
Testing
TL;DR
12. Testing
Testing Basics
Naming Tests
The Testing Environment
The Testing Traits
WithoutMiddleware
DatabaseMigrations
DatabaseTransactions
Application Testing
TestCase
“Visiting” Routes
Custom Application Testing Assertions
JSON and Non-visit() Application Testing Assertions
Clicking and Forms
Jobs and Events
Authentication and Sessions
Artisan and Seed
Mocking
Mockery
Mocking Facades
TL;DR
13. Writing APIs
The Basics of REST-Like JSON APIs
Controller Organization and JSON Returns
Reading and Sending Headers
Sending Response Headers in Laravel
Reading Request Headers in Laravel
Eloquent Pagination
Sorting and Filtering
Sorting Your API Results
Filtering Your API Results
Transforming Results
Writing Your Own Transformer
Nesting and Relationships
API Authentication with Laravel Passport
A Brief Introduction to OAuth 2.0
Installing Passport
Passport’s API
Passport’s Available Grant Types
Password grant
Authorization code grant
Personal access tokens
Tokens from Laravel session authentication (synchronizer tokens)
Managing Clients and Tokens with the Passport API and the Vue Components
The routes
The Vue components
Passport Scopes
Laravel 5.2+ API Token Authentication
Testing
TL;DR
14. Storage and Retrieval
Local and Cloud File Managers
Configuring File Access
Using the Storage Facade
Adding Additional Flysystem Providers
Basic File Uploads and Manipulation
Sessions
Accessing the Session
The Methods Available on Session Instances
Flash Session Storage
Cache
Accessing the Cache
The Methods Available on Cache Instances
Cookies
Cookies in Laravel
Accessing the Cookie Tools
The Cookie facade
The cookie() global helper
Cookies on request and response objects
Reading cookies from request objects
Setting cookies on response objects
Full-Text Search with Laravel Scout
Installing Scout
Marking Your Model for Indexing
Searching Your Index
Queues and Scout
Perform Operations Without Indexing
Manually Trigger Indexing via Code
Manually Trigger Indexing via the CLI
Testing
File Storage
Uploading fake files
Returning fake files
Session
Cache
Cookies
TL;DR
15. Mail and Notifications
Mail
“Classic” Mail
Basic “Mailable” Mail Usage
Mail Templates
Methods Available in build()
Attachments and Inline Images
Queues
queue()
later()
Specifying the queue or connection
Local Development
The log driver
Mailtrap.io
Universal to
Notifications
Defining the via() Method for Your Notifiables
Sending Notifications
Sending notifications using the Notifiable trait
Sending notifications with the Notification facade
Queueing Notifications
Out-of-the-Box Notification Types
Email notifications
Database notifications
Broadcast notifications
SMS notifications
Slack notifications
Testing
Mail
Notifications
TL;DR
16. Queues, Jobs, Events, Broadcasting, and the Scheduler
Queues
Why Queues?
Basic Queue Configuration
Queued Jobs
Creating a job
Pushing a job onto a queue
Customizing the connection
Customizing the queue
Customizing the delay
Running a Queue Worker
Handling Errors
Exceptions in handling
Limiting the number of tries
Handling failed jobs
Controlling the Queue
Queues Supporting Other Functions
Events
Firing an Event
Listening for an Event
Event subscribers
Broadcasting Events over WebSockets, and Laravel Echo
Configuration and Setup
Broadcasting an Event
Receiving the Message
Advanced Broadcasting Tools
Excluding the current user from broadcast events
The broadcast service provider
Binding authorization definitions for WebSocket channels
Laravel Echo (the JavaScript Side)
Bringing Echo into your project
Using Echo for basic event broadcasting
Private channels and basic authentication
Presence channels
Excluding the current user
Subscribing to notifications with Echo
Scheduler
Available Task Types
Available Time Frames
Blocking and Overlap
Handling Task Output
Task Hooks
Testing
TL;DR
17. Helpers and Collections
Helpers
Arrays
Strings
Application Paths
URLs
Misc
Collections
The Basics of Collections
A Few Methods
TL;DR
Glossary
Index
Laravel: Up and Running A Framework for Building Modern PHP Apps Matt Stauffer
Laravel: Up and Running by Matt Stauffer Copyright © 2017 Matt Stauffer. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Allyson MacDonald Production Editor: Colleen Lobner Copyeditor: Rachel Head Proofreader: Kim Cofer Indexer: Angela Howard Interior Designer: David Futato Cover Designer: Randy Comer Illustrator: Rebecca Demarest December 2016: First Edition
Revision History for the First Edition 2016-11-14: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491936085 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Laravel: Up and Running, the cover image of a gemsbok, and related trade dress are trademarks of O’Reilly Media, Inc. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-491-93608-5 [LSI]
Dedication This book is dedicated to my gracious and inspiring wife, Tereva, my joyful and courageous son, Malachi, and my beautiful daughter, Mia, who spent the majority of this book’s creation in her mama’s belly.
Preface The story of how I got started with Laravel is a common one: I had written PHP for years, but I was on my way out the door, pursuing the power of Rails and other modern web frameworks. Rails in particular had a lively community, a perfect combination of opinionated defaults and flexibility, and the power of Ruby Gems to leverage prepackaged common code. Something kept me from jumping ship, and I was glad for that when I found Laravel. It offered everything I was drawn to in Rails, but it wasn’t just a Rails clone; this was an innovative framework with incredible documentation, a welcoming community, and clear influences from many languages and frameworks. Since that day I’ve been able to share my journey of learning Laravel through blogging and speaking at conferences; I’ve written dozens of apps in Laravel for side and work projects, and I’ve met thousands of Laravel developers online and in person. I have plenty of tools in my toolkit at our consultancy, but I am honestly happiest when I sit down in front of a command line and type laravel new project.
What This Book Is About This is not the first book about Laravel, and it won’t be the last. I don’t intend for this to be a book that covers every line of code or every implementation pattern. I don’t want this to be the sort of book that goes out of date when a new version of Laravel is released. Instead, its primary purpose is to provide developers with a high-level overview and concrete examples to learn what they need to get started, as quickly as possible. Rather than mirroring the docs, I want to help you understand the foundational concepts behind Laravel. Laravel is a powerful and flexible PHP framework. It has a thriving community and a wide ecosystem of tools, and as a result it’s growing in appeal and reach. This book is for developers who already know how to make websites and applications and want to quickly learn how to do so in Laravel. Laravel’s documentation is thorough and excellent. If you find that I don’t cover any particular topic deeply enough for your liking, I encourage you to visit the online documentation and dig deeper into that particular topic. I think you will find the book a comfortable balance between high-level introduction and concrete application, and by the end you should feel comfortable writing an entire application in Laravel, from scratch. And, if I did my job well, you’ll be excited to try.
分享到:
收藏