modern php/laravel talk

66
Modern PHP With Laravel and Symfony

Upload: eduardo-trujillo

Post on 12-Jul-2015

643 views

Category:

Software


1 download

TRANSCRIPT

Page 1: Modern PHP/Laravel Talk

Modern PHPWith Laravel and Symfony

Page 2: Modern PHP/Laravel Talk

Eduardo Trujillo

chromabits.com

Page 3: Modern PHP/Laravel Talk

PHP

Page 4: Modern PHP/Laravel Talk

MODERN PRACTICES IN

PHP

Page 5: Modern PHP/Laravel Talk
Page 6: Modern PHP/Laravel Talk
Page 7: Modern PHP/Laravel Talk
Page 8: Modern PHP/Laravel Talk
Page 9: Modern PHP/Laravel Talk
Page 10: Modern PHP/Laravel Talk
Page 11: Modern PHP/Laravel Talk

PHPsucks?

Page 12: Modern PHP/Laravel Talk

THE BIG PROBLEM

Page 13: Modern PHP/Laravel Talk

PHP lets you write really bad code & applications…

and THEY will still work

Page 14: Modern PHP/Laravel Talk

There is a lot of bad PHP code out there

Page 15: Modern PHP/Laravel Talk

The learning “curve” for making websites on PHP can be “easy”

but writing really good PHP applications takes a bit more work

Criticism: Partly because of the language and partly because the community

Page 16: Modern PHP/Laravel Talk

…But

PHP drives many of the most popular websites and it’s usage keeps growing

http://trends.builtwith.com/framework

Page 17: Modern PHP/Laravel Talk
Page 18: Modern PHP/Laravel Talk

The Right

way

http://www.phptherightway.com

Page 19: Modern PHP/Laravel Talk

• If we follow a good set of standards and patterns

• High-quality PHP apps

• Less prone to breaking and safer

• Easier to maintain

THE GENERAL IDEA IS

Page 20: Modern PHP/Laravel Talk

Development setup

Page 21: Modern PHP/Laravel Talk

Development setup

• Your dev setup is your tool belt

• Your tools should help you achieve your goal, not get in the way

• Classic PHP xAMP development setups are a pain to setup and maintain (e.g. /etc/hosts)

• Text editor vs IDE

Page 22: Modern PHP/Laravel Talk

Development setup

Page 23: Modern PHP/Laravel Talk

dockeR

Need to run an Apache 2 server with PHP 5.6?:

docker run -it --rm --name my-app -v "$(pwd)":/var/www/html php:5.6-apache

This will mount the current dir into the docker container and start an Apache 2 server on port 80

https://registry.hub.docker.com/_/php/

Page 24: Modern PHP/Laravel Talk

homestead

http://www.sitepoint.com/6-reasons-move-laravel-homestead/

• Vagrant VM

• Laravel is pre-setup

• MySQL and Postgres

• Node, bower, grunt

• HHVM, Nginx

• Redis & Memcached

• HipChat extension

http://laravel.com/docs/4.2/homestead

Page 25: Modern PHP/Laravel Talk

Editors

• PHPStorm 😀

• Eclipse PDT

• Atom, Sublime Text, vim and emacs (with the right plugins)

suggestions

Page 26: Modern PHP/Laravel Talk

phpstorm: The tiny details matter

Page 27: Modern PHP/Laravel Talk

phpstorm: The NOT-SO-tiny details ALSO matter

Page 28: Modern PHP/Laravel Talk

spf13-vimhttp://vim.spf13.com

Page 29: Modern PHP/Laravel Talk

Code quality

• PHP Mess Detector: Detect potential problems with your code

• PHP Code Sniffer: Make sure your code follows some standard, like PSR-2

TOOLS

Page 30: Modern PHP/Laravel Talk

Artisan CLI• Laravel’s CLI (Built upon Symfony’s Console)

• Possibly similar to Rails: rails and rake

• php artisan serve

• php artisan migrate

• php artisan make:controller (Scaffolding)

• php artisan tinker (A REPL for playing with classes/models in your application)

Page 31: Modern PHP/Laravel Talk

OOP and autoloading

OOP and autoloading

OOP and autoloading

Page 32: Modern PHP/Laravel Talk

Object Oriented PHP

• This should not be new to everyone

• PHP 5 added objects. Following versions have added even more OOP features

• Some ideas:

• Namespaces: Package your code into modules

• Traits: Reused code fragments in multiple classes

• Interfaces: Very useful for mocking during testing and making your classes less dependent on each other

Page 33: Modern PHP/Laravel Talk

Autoloading• Complex PHP projects can have a lot of classes

• The problem: requiring/including php files from each other, making your project some sort of file dependency spaghetti

• The other problem: Your project’s git repo is full of third-party code that is slowly aging

• git submodules: Not usually recommended

http://somethingsinistral.net/blog/git-submodules-are-probably-not-the-answer/

Page 34: Modern PHP/Laravel Talk

Composer• Like npm

• composer.json

• Interactive CLI

• Supports private repositories

• .gitignore: /vendor

Page 35: Modern PHP/Laravel Talk

autoload.php• /vendor/autoload.php: The last file you’ll ever need

to include/require in your app (usually)

• PSR-4 and PSR-2

• Automatically loads classes from your own project and dependencies you have included in your project

• Both Laravel and Symfony are built around it

Page 36: Modern PHP/Laravel Talk

MVCMVC

Page 37: Modern PHP/Laravel Talk

MVC: Routing

• mysite.com/index.php

• mysite.com/blog/post.php?id=34

• mysite.com/cart/shopping.php?action=buy&id=56

Page 38: Modern PHP/Laravel Talk

MVC: Routing• Anti-pattern: Using the file system as your routing strategy

• Why is it bad?

• It’s not very flexible and it’s hard to maintain

• Your application has multiple entry points

• It’s prone to unexpected behavior

• Does not follow PSR-2 standards

• You have to mess a lot with .htaccess and mod_rewrite

Page 39: Modern PHP/Laravel Talk

routers• A component inside your application that:

• Parses all the HTTP request info

• Decides what to do next, like executing a controller method

• Laravel’s Router: Easy and simple to use

• Symfony’s HttpKernel Component: More complex but manages the whole request lifecycle

Page 40: Modern PHP/Laravel Talk

Routing in Laravel

SIMPLE GET ROUTE

WITH PATTERN MATCHING

Page 41: Modern PHP/Laravel Talk

Http kernel: handling the whole Request

lifecycle

More at: http://symfony.com/doc/current/components/http_kernel/introduction.html

Page 42: Modern PHP/Laravel Talk

MVC: Templating• Anti-pattern: Combining business logic with your

views

• Embedding HTML inside PHP files has always been a feature in the language. However, that does not mean you should use it 😜

• Removing business logic from templates and moving them into controllers helps with maintainability and clarity

Page 43: Modern PHP/Laravel Talk

avoid this:

This is on a W3Schools PHP tutorial:

http://www.w3schools.com/php/php_forms.asp

Page 44: Modern PHP/Laravel Talk

definitely avoid this:

http://www.w3schools.com/php/php_mysql_select.asp

Page 45: Modern PHP/Laravel Talk

Template Engines

• Parse templates files and render the HTML output based on the data provided by the controller

• Most of them do variable escaping automatically

• Some template formats feature structures similar to programming languages, others are almost completely devoid of logic

• They can plug right in into Symfony’s HttpKernel

Page 46: Modern PHP/Laravel Talk

Template engines

• Laravel’s Blade

• Symfony’s Templating Component

• Mustache.js

• Twig

• XHP (If you work for Facebook)

suggestions

Page 47: Modern PHP/Laravel Talk

templating with blade

MAIN View EXTENDING

RENDERING

Page 48: Modern PHP/Laravel Talk

Abstracting away from the dB

Page 49: Modern PHP/Laravel Talk

Databases• Anti-pattern: Writing SQL queries everywhere in your code for the

same repetitive actions

• Why not?

• Makes your code dependent on the database server implementation

• Hard to maintain: Everyone involved has to know SQL very well

• Vulnerable: The famous SQL injection

• A lot of string concatenation/formatting/purification/escaping

Page 50: Modern PHP/Laravel Talk

ORMS• As a developer, you start interacting more with your own

classes rather than the underlying DB implementation

• Some say ORMs are not very flexible. However, many of them have functions for securely writing complex queries

• Laravel comes with Eloquent: It is very light, but it does enforce that your schema follows a few conventions

• Doctrine: A very popular PHP ORM. It has its own query language and can be added to existing applications

Page 51: Modern PHP/Laravel Talk

EloquentCreating UPDATING

QUERYING

Page 52: Modern PHP/Laravel Talk

Testing

Page 53: Modern PHP/Laravel Talk

Testing• Why? Detect problems while developing a feature and

checking for regressions in the future

• PHPUnit for Unit Testing

• Mockery: a library for building mocks of classes for your tests

• Laravel: Comes with some tools to test controllers and views

• Dependencies: Interfaces > Concrete Classes (more on that later)

Page 54: Modern PHP/Laravel Talk

Dependency injection

• Anti-pattern: Make everything static and make classes dependent on concrete classes rather than interfaces (Class coupling)

• Why is it bad?

• It’s harder to mock and test static classes

• It’s easier to create a mock that simply implements an interface

• It becomes harder to create multiple instances of your application. (Yes, there are cases where you might want to do this: Sub-requests)

• Memory usage increases since there are multiple instances of the same class

Page 55: Modern PHP/Laravel Talk

Dependency injection

• Constructor Injection: The pattern is to put all your dependencies in your class constructor and keep references to them through protected/private properties

Page 56: Modern PHP/Laravel Talk

However, doing this is not enough

Passing instance references along solves part of the problem, but you still have to deal with passing the

right parameters to class constructors

Page 57: Modern PHP/Laravel Talk

service-oriented architecture

• Most web apps need access to certain components throughout the entire codebase

• We call them: Services

• It’s becoming a common concept in web development in general (See Angular Services/Factories)

• Factory class/function: Builds an instance of a service

• Service provider: “Registers” multiple factories within the application

Page 58: Modern PHP/Laravel Talk

Ioc containers• Inversion of control: Method for avoiding hard-coded dependencies on

classes.

• It’s one central repository of factories and class instances (usually one instance of the container per application)

• Service providers register factories on the container

• The container uses factories to build instances of services when they are requested

• Support for lazy-loading

• Laravel and Symfony have their own container implementations

Page 59: Modern PHP/Laravel Talk

LAravel’s container

The default setup is smart enough to figure out how to build certain classes and even inject their dependencies

Page 60: Modern PHP/Laravel Talk

Laravel Facades

Static classes or IoC container?

Page 61: Modern PHP/Laravel Talk

Laravel Facades

• The benefits of an IoC container while keeping the syntactic sugar of static methods

• Assumes that there will only be one container

• A facade acts as a proxy for the instance in the container

• Con: Not supported very well by IDEs, as result they are no longer the main DI method in Laravel 5

Page 62: Modern PHP/Laravel Talk

Queues• Some things in your web app can take a long time to process

• The goal is to give user feedback as soon as possible (The refresh problem)

• Queues allow us to schedule backgrounds jobs and respond to the user faster

• Queue workers actively listen on the queue for jobs

• Workers can be on separate hosts, alleviating the load on the front-end web servers

Page 63: Modern PHP/Laravel Talk

Queues

• Laravel provides a very abstracted and easy interface for interacting with queues

• The equivalent of an Database ORM for Redis, SQS and Iron.mq

• Workers share the codebase!

Page 64: Modern PHP/Laravel Talk

Queues in laravel

Worker class:

On your controller:

Page 65: Modern PHP/Laravel Talk

A Few more things™

• Some extra things you should take a look at:

• HHVM & Hack (Gotta have that type safety)

• PHP 7 (a.k.a PHPNG)

• Database Migrations

• ErrorExceptions

• Input Validation

Page 66: Modern PHP/Laravel Talk

Q&A

Q&A

Q&A