52
THE PHP FRAMEWORK FOR WEB ARTISANS 1 By Viral Solani Tech Lead Cygnet Infotech

Introduction to Laravel Framework (5.2)

Embed Size (px)

Citation preview

Page 1: Introduction to Laravel Framework (5.2)

THE PHP FRAMEWORK FOR WEB ARTISANS

1

By Viral SolaniTech Lead

Cygnet Infotech

Page 2: Introduction to Laravel Framework (5.2)

Why Laravel ? Good Question !

• Inspired from battle tested frameworks (ROR , .Net)• Built on top of symfony2 components• Guides new developers to use good practices.• Easy Learning Curve.• Survived the PHP Framework War , now its one of the most used frameworks.• Expressive Syntax • Utilizes the latest PHP features (Namespaces , Interface , PSR-4

Auto loading , Ioc )

•Active and growing community that can provide quick support and answers

•Out of box Authentication , Localization etc.

• Well Documented (http://laravel.com/docs)2

Page 3: Introduction to Laravel Framework (5.2)

Modern Framework

• Routing

• Controllers

• Template Systems (Blade)

• Validation

• ORM (Eloquent)

• Authentication out of the box

• Logging

• Events

• Mail

➢ Queues ➢ Task Scheduling➢ Elixier➢ Localization➢ Unit Testing (PHPunit)➢ The list goes on….

3

Page 4: Introduction to Laravel Framework (5.2)

What is Composer ?

•Composer is a tool for Dependency Management for PHP.

•Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine.

4

Page 5: Introduction to Laravel Framework (5.2)

Your Awesome

PHPProject

(1) Read composer.json

(2) Find Library form Packagist

(3) Download Library(4) Library downloadedon your project

How Composer works?

5

Page 6: Introduction to Laravel Framework (5.2)

How to install Laravel ??

You can install Laravel by Three ways

- via laravel installer

- via composer

- clone from github

6

Page 7: Introduction to Laravel Framework (5.2)

This will download laravel installer via composer-composer global require "laravel/installer"

When installer added this simple command will create app-laravel new <app name>

* Do not forget to add ~/.composer/vendor/bin to your PATH variable in ~/.bashrc

Via Laravel Installer

7

Page 8: Introduction to Laravel Framework (5.2)

Via composer

- composer create-project laravel/laravel your-project-name

Get from GitHub-https://github.com/laravel/laravel-And then in the project dir run “composer install” to get all needed packages

Other Options

8

Page 9: Introduction to Laravel Framework (5.2)

Laravel Directory Structure

App

Bootstrap

Config

Database

Public

Resources

Storage

Tests

Vendor

.env

.env.example

.gitattribuites

.gitignore

Artisan

Composer.lock

Composer.json

Gulpfile.js

Package.json

Phpunit.xml

Readme.md

Server.php

9

Page 10: Introduction to Laravel Framework (5.2)

Laravel Directory Structure : App

10

Page 11: Introduction to Laravel Framework (5.2)

Routes

• Create routes at: app/Http/routes.php• include() additional route definitions if needed• Below Methods are available.

– Route::get();– Route::post();– Route::put();– Route::patch();– Route::delete();– Route::any(); //all of above

11

Page 12: Introduction to Laravel Framework (5.2)

Routes

app/Http/routes.php

Route::get('/', function(){ echo ‘Boom!’;

});

12

Page 13: Introduction to Laravel Framework (5.2)

Routes

13

Page 14: Introduction to Laravel Framework (5.2)

Controllers

Command : php artisan make:controller PhotoController

• The Artisan command will generate a controller file at app/Http/Controllers/PhotoController.php.

• The controller will contain a method for each of the available resource operations.

14

Page 15: Introduction to Laravel Framework (5.2)

Resource Controller

php artisan make:controller PhotoController --resource

Route::resource('photos', 'PhotoController');

15

Page 16: Introduction to Laravel Framework (5.2)

Views

• Views contain the HTML served by your application and separate your controller / application logic from your presentation logic.

• Views are stored in the resources/views directory.

• Can be separated in subdirectories• Can be both blade or simple php files

16

Page 17: Introduction to Laravel Framework (5.2)

Blade Template Engine

• Laravel default template engine

• Files need to use .blade.php extension

• Driven by inheritance and sections

• all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

• Extensible for adding new custom control structures (directives)

17

Page 18: Introduction to Laravel Framework (5.2)

Defining a Layout

<!-- Stored in resources/views/layouts/app.blade.php --><html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @show

<div class="container"> @yield('content') </div> </body></html>

18

Page 19: Introduction to Laravel Framework (5.2)

Extending a Layout

<!-- Stored in resources/views/child.blade.php -->

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar') @parent

<p>This is appended to the master sidebar.</p>@endsection

@section('content') <p>This is my body content.</p>@endsection

19

Page 20: Introduction to Laravel Framework (5.2)

View System

• Returning a view from a route

Route::get('/', function(){

return view('home.index');//resources/views/home/index.blade.php

});

• Sending data to view

Route::get('/', function(){

return view(‘home.index')->with('email', '[email protected]');});

20

Page 21: Introduction to Laravel Framework (5.2)

Models

• Command to create model : php artisan make:model User

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model{ /** * The table associated with the model. * * @var string */ protected $table = 'tablename';}

21

Page 22: Introduction to Laravel Framework (5.2)

Eloquent ORM

• Active Record

• Table – plural, snake_case class name• Has a lot of useful methods• is very flexible• Has built in safe delete functionality• Has built in Relationship functionality

• Timestamps• Has option to define scopes

22

Page 23: Introduction to Laravel Framework (5.2)

Eloquent ORM - Examples

$flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10) ->get();

// Retrieve a model by its primary key...$flight = App\Flight::find(1);

// Retrieve the first model matching the query constraints...$flight = App\Flight::where('active', 1)->first();

$flights = App\Flight::find([1, 2, 3]);

//Retrieving Aggregates

$count = App\Flight::where('active', 1)->count();$max = App\Flight::where('active', 1)->max('price');

23

Page 24: Introduction to Laravel Framework (5.2)

Query Builder

• The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.

• Simple and Easy to Understand• Used extensively by Eloquent ORM

24

Page 25: Introduction to Laravel Framework (5.2)

Query Builder - Examples

//Retrieving All Rows From A Table

$users = DB::table('users')->get();

//Retrieving A Single Row / Column From A Table

$user = DB::table('users')->where('name', 'John')->first();

echo $user->name;

//Joins

$users = DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get();

25

Page 26: Introduction to Laravel Framework (5.2)

Migrations & Seeders

• “Versioning” for your database , and fake data generator

• php artisan make:migration create_users_table

• php artisan make:migration add_votes_to_users_table

• php artisan make:seeder UsersTableSeeder

• php artisan db:seed

• php artisan db:seed --class=UsersTableSeeder

• php artisan migrate:refresh --seed26

Page 27: Introduction to Laravel Framework (5.2)

Examples of Migration & Seeding

27

Page 28: Introduction to Laravel Framework (5.2)

Middleware

• Route Filters

• Allows processing or filtering of requests entering the system

• Better , Faster , Stronger

• Defining Middleware : php artisan make:middleware Authenticate

• If you want a middleware to be run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/Kernel.php class.

28

Page 29: Introduction to Laravel Framework (5.2)

Middleware : Example

29

Page 30: Introduction to Laravel Framework (5.2)

Middleware - Popular Uses :

• Auth

• ACL

• Session

• Caching

• Debug

• Logging

• Analytics

• Rate Limiting

30

Page 31: Introduction to Laravel Framework (5.2)

Requests

• Command to Create Request php artisan make:request StoreBlogPostRequest

• Validators That are executed before hitting the action of the Controller

• Basically Designed for Authorization and Form validation

31

Page 32: Introduction to Laravel Framework (5.2)

Requests : Example

32

Page 33: Introduction to Laravel Framework (5.2)

Service Providers

• Command to create Service Provider : php artisan make:provider

• Located at : app/Providers

• Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers.

• But, what do we mean by "bootstrapped"? In general, we mean registering things, including registering service container bindings, event listeners, middleware, and even routes. Service providers are the central place to configure your application.

33

Page 34: Introduction to Laravel Framework (5.2)

Service Container

• The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection.

• Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

• You need to bind all your service containers , it will be most probably registered within service providers.

34

Page 35: Introduction to Laravel Framework (5.2)

Service Container : Example

35

Page 36: Introduction to Laravel Framework (5.2)

Facades

• Facade::doSomethingCool()

• Isn’t that a static method? - Well, no

• A «static» access to underlying service

• Look like static resources, but actually uses services underneath

• Classes are resolved behind the scene via Service Containers• Laravel has a lot usefull usages of Facades like

– App::config()– View::make()– DB::table()– Mail::send()– Request::get()– Session::get()– Url::route()– And much more…

36

Page 37: Introduction to Laravel Framework (5.2)

Encryption

• Simplified encryption using OpenSSL and the AES-256-CBC cipher

• Available as Facade Crypt::encrypt() &Crypt::decrypt()

• Before using Laravel's encrypter, you should set the key option of your config/app.phpconfiguration file to a 32 character, random string. If this value is not properly set, all values encrypted by Laravel will be insecure.

37

Page 38: Introduction to Laravel Framework (5.2)

Artisan (CLI)

• Generates Skeleton Classes • It runs migration and seeders• It catches a lot of stuff (speed things up)• It execute custom commands • Command : Php artisan

38

Page 39: Introduction to Laravel Framework (5.2)

Ecosystem

• Laravel

• Lumen

• Socialite

• Cashier

• Elixir

• Envoyer

• Spark

• Homestead

• Valet

• Forge

39

Page 40: Introduction to Laravel Framework (5.2)

Lumen

• Micor-framework for Micro-services

• Sacrifices configurability for speed

• Easy upgrade to a full Laravel application

40

Page 41: Introduction to Laravel Framework (5.2)

Socialite

• Integrates Social authentication functionality

• Almost for all popular platforms available

• http://socialiteproviders.github.io

41

Page 42: Introduction to Laravel Framework (5.2)

Cashier

• Billing without the hassle

• Subscription logic included

• Easy to setup

42

Page 43: Introduction to Laravel Framework (5.2)

Elixir

• Gulp simplified

• Compilation, concatenation, minifaction, auto-prefixing,…

• Support for

– Source Maps

– CoffeScript

– Browserify

– Babel

– …

43

Page 44: Introduction to Laravel Framework (5.2)

Spark

• Billing

• Team management

• Invitations

• Registration

• 2-factor auth

• …

44

Page 45: Introduction to Laravel Framework (5.2)

Homestead

• Comes with everything you need– Ubuntu

– PHP 5.6 & 7

– Nginx

– MySQL & Postgres

– Node

– Memcached

– Redis

– ---

45

Page 46: Introduction to Laravel Framework (5.2)

Forge

• Automates the process to setup a server

• You don’t need to learn how to set up one

• Saves you the effort of settings everything up

• Globally, saves you ridiculous amounts of time

46

Page 47: Introduction to Laravel Framework (5.2)

Envoyer (!= Envoy)

• Zero downtime deployments

• Seamless rollbacks

• Cronjobs monitoring with heartbeats

• Deployment health status

• Deploy on multiple servers at once

47

Page 48: Introduction to Laravel Framework (5.2)

Community

• Slack http://larachat.co/

• Forum https://laracasts.com/discuss• Forum http://laravel.io/forum

• Twitter https://twitter.com/laravelphp• GitHub https://github.com/laravel/laravel

48

Page 49: Introduction to Laravel Framework (5.2)

Conference

• LaraconUS July 27-29, Kentucky USAhttp://laracon.us/

• LaraconEU August 23-24, Amsterdam NL http://laracon.eu

49

Page 50: Introduction to Laravel Framework (5.2)

Learning

• Laravel Documentation https://laravel.com/

• Laracastshttps://laracasts.com/

50

Page 51: Introduction to Laravel Framework (5.2)

CMS

• AsgardCMS https://asgardcms.com/

• OctoberCMS http://octobercms.com/

• Laravel 5 Boilerplate

https://github.com/rappasoft/laravel-5-boilerplate

51

Page 52: Introduction to Laravel Framework (5.2)

52