modern php/laravel talk

Post on 12-Jul-2015

645 Views

Category:

Software

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Modern PHPWith Laravel and Symfony

Eduardo Trujillo

chromabits.com

PHP

MODERN PRACTICES IN

PHP

PHPsucks?

THE BIG PROBLEM

PHP lets you write really bad code & applications…

and THEY will still work

There is a lot of bad PHP code out there

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

…But

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

http://trends.builtwith.com/framework

The Right

way

http://www.phptherightway.com

• 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

Development setup

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

Development setup

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/

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

Editors

• PHPStorm 😀

• Eclipse PDT

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

suggestions

phpstorm: The tiny details matter

phpstorm: The NOT-SO-tiny details ALSO matter

spf13-vimhttp://vim.spf13.com

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

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)

OOP and autoloading

OOP and autoloading

OOP and autoloading

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

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/

Composer• Like npm

• composer.json

• Interactive CLI

• Supports private repositories

• .gitignore: /vendor

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

MVCMVC

MVC: Routing

• mysite.com/index.php

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

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

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

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

Routing in Laravel

SIMPLE GET ROUTE

WITH PATTERN MATCHING

Http kernel: handling the whole Request

lifecycle

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

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

avoid this:

This is on a W3Schools PHP tutorial:

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

definitely avoid this:

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

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

Template engines

• Laravel’s Blade

• Symfony’s Templating Component

• Mustache.js

• Twig

• XHP (If you work for Facebook)

suggestions

templating with blade

MAIN View EXTENDING

RENDERING

Abstracting away from the dB

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

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

EloquentCreating UPDATING

QUERYING

Testing

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)

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

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

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

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

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

LAravel’s container

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

Laravel Facades

Static classes or IoC container?

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

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

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!

Queues in laravel

Worker class:

On your controller:

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

Q&A

Q&A

Q&A

top related