Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PHP Belfast Laravel Presentation

David Frame
November 07, 2013

PHP Belfast Laravel Presentation

A brief introduction to the Laravel PHP framework and its key features.

David Frame

November 07, 2013
Tweet

More Decks by David Frame

Other Decks in Programming

Transcript

  1. About me Started using PHP around 1999-2000. Primarily interested in

    OOP, design patterns, frameworks, CMS development and R&D. Research Developer at Tibus / Simply Zesty (2003-2012). Senior Developer at Blue Cube / AV Browne (2013). Senior Developer at 31interactive (2013-present).
  2. The PHP Renaissance Better internals (namespaces, closures, traits, etc). Better

    tools (Composer, CLI utilities). Better methodologies (OOP, TDD, DI). Better standards (PSR). Better frameworks (Symfony2, ZF2, Slim, Aura, Laravel).
  3. About this presentation It's a VERY brief introduction! Covers Laravel's

    six main elements as I see them. Will hopefully prompt you to learn more about it. It's not a sermon!
  4. So what is Laravel? A modern PHP 5.3+ full-stack framework

    first released in July 2011. Very loosely based off Codeigniter. Makes use of several popular and highly tested components such as Symfony's HttpKernel & HttpFoundation, Monolog, Swiftmailer, etc.
  5. The six areas I'll be covering 1. Syntax. 2. Artisan

    command line tool. 3. Request routing. 4. Query Builder & Eloquent database layers. 5. Blade templating engine. 6. IoC container.
  6. Expressiveness $articles = Article::where('online', '=', 1) ->orderBy('date', 'desc') ->skip(10) ->take(5)

    ->get(); Redirect::to('login') ->with('message', 'Login failed'); Cookie::forever('remember_me', 1);
  7. Facades Facades are static wrappers to instantiated objects. They provide

    a quick, readable way to access Laravel's various components. Big misconception: Laravel is NOT a static framework. Since these facades are syntactic sugar you can bypass them for mocks and tests! You can easily create your own facades or 'rewire' the existing ones.
  8. Facades example $appName = Config::get('application.name'); $filesystem = new Filesystem(...); $fileloader

    = new Fileloader($filesysyem); $config = new Config($fileloader, 'dev'); $appName = $config->get('application.name');
  9. Powerful command line tool Based off Symfony's Console component. Allows

    a number of application management tasks to be run from the CLI (code generation, DB migrations, etc). Easily customisable - write your own tasks!
  10. Implicit routing Route::get('news', function() { return '<p>News page</p>'; }); Route::get('news/{id}',

    function($id) { return '<p>Article with id ' . $id . '</p>'; })->where('id', '[0-9]+'); Route::post('enquiry/submit', function() { return 'Posted: ' . print_r($_POST, true); });
  11. Routing to controllers Route::controller('news', 'NewsController'); Route::controller('login', 'LoginController'); Route::controller('admin', 'AdminController'); class

    NewsController { public function getIndex() { ... } public function getArticle() { ... } public function postComment() { ... } }
  12. Routing to resources (REST) Route::resource('news', 'NewsController'); class NewsController { public

    function index() { ... } public function create() { ... } public function store() { ... } public function show() { ... } public function edit() { ... } public function update() { ... } public function destroy() { ... } }
  13. Resource routes -> methods GET /news -> NewsController::index() GET /news/create

    -> NewsController::create() POST /news -> NewsController::store(); GET /news/{id} -> NewsController::show($id) GET /news/{id}/edit -> NewsController::edit($id) PUT/PATCH /news/{id} -> NewsController::update($id) DELETE /news/{id} -> NewsController::destroy($id) For the previous NewsController route we would have:
  14. Route names & filters Route::get('news/{id}', array('as' => 'article', function() {

    return '<p>News article!</p>'; }}); ! Redirect::route('article', array('id' => 1)); Route::filter('auth', function() { if (Auth::guest()) { return Redirect::to('login'); } }); ! Route::get('admin', array('before' => 'auth', function() { return '<p>Welcome to the admin area!</p>'; }));
  15. Query Builder A feature-rich database abstraction layer implemented using PDO.

    Allows you to manipulate a database using object methods calls or using raw SQL. Fluent interface (chainable methods). Clean, English-like syntax. Supports 'complicated' database operations such as joins, aggregates, unions and even caching. Comparable to Zend\Db\Sql, Pear's MDB2 package.
  16. Selects and Inserts DB::table('posts')->where('online', '=', 1) ->orderBy('date', 'desc')->take(5)->get(); DB::table('posts')->where('id', '=',

    15)->first(); DB::table('posts')->insert(array( 'title' => 'Test Article', 'date' => '2013-11-05', 'online' => 1 ));
  17. Updates and Deletes DB::table('posts') ->where('id', '=', 15) ->update(array( 'title' =>

    'Updated Test Article', 'online' => 0 ) ); DB::table('posts') ->where('id', '=', 15) ->delete();
  18. Other handy features DB::table('posts')->where('id', '=', 15) ->pluck('title'); DB::table('posts') ->join('categories', 'posts.category_id',

    '=', 'categories.id') ->where('categories.id', '=', 5) ->get(); DB::table('reviews')->avg('rating');
  19. Eloquent Object Relational Mapper built on top of Query Builder

    - it has identical syntax! Allows database entities to be mapped to PHP code, commonly referred to as Models. A model definition can be quickly set up using an appropriately named class (no getter/setters required!) Powerful features such as relationships, eager loading, event triggers, accessors/mutators and a lot more! Comparable to Zend\Db\TableGateway, Doctrine, Propel, Redbean.
  20. Model Class class Post extends Eloquent { } class Post

    extends Eloquent { protected $table = 'newsposts'; public function summary() { return truncate($this->content, 150); } }
  21. Selects and Inserts Post::where('date', '<=', DB::raw('CURDATE()')) ->andWhere('online', '=', 1) ->get();

    Post::find(5); $post = new Post(); $post->title = 'New Article'; $post->date = new DateTime(); $post->online = true; $post->save();
  22. Updates, Deletes & Conversions $post = Post::find(5); $post->title = 'Updated

    News Article'; $post->online = false; $post->save(); Post::find(5)->delete(); // Or... Post::destroy(5); Post::all()->toArray(); Post::find(5)->toJson();
  23. Relationship definition class Post extends Eloquent { public function comments()

    { return $this->hasMany('Comment'); } } ! ! class Comment extends Eloquent { public function post() { return $this->belongsTo('Post'); } }
  24. Relationship usage $post = Post::find(5); echo '<h2>' . $post->title .

    '</h2>'; foreach ($post->comments as $comment) { echo ' <p>' . $comment->text . '</p> <p>' . $comment->author . '</p> '; } $comment = Comment::find(25); echo '<h2>' . $comment->post->title . '</h2>';
  25. Quick and easy Pagination $posts = Post::paginate(10); ... Produces Bootstrap-compatible

    paging links! foreach ($posts as $post) { echo '<h2>' . $post->title . '</h2>'; echo '<p>' . $post->summary . </p>'; } ! echo $posts->links();
  26. Overview Blade is a quick and relatively simple template engine

    for rendering your views. Features many of the core functions found in other popular engines such as Twig and Smarty. Since Blade views are PHP scripts, you can use PHP code directly in your templates (with caution!) Inheritance-driven to allow for multiple layouts, sections, etc.
  27. Basic template @include('inc/header') ! <h1>{{{ $pageTitle }}}</h1> ! <p>{{ count($posts)

    }} articles to display!</p> ! @foreach ($posts as $post) <h2>{{{ $post->title }}}</h2> @if ($post->summary) <p>{{{ $post->summary }}}</p> @endif @endforeach ! @include('inc/footer');
  28. Rendering a view Route::get('news', function() { ! $posts = Post::all();

    ! return View.make('news') ->with('pageTitle', 'News') ->with('posts', $posts); ! }); Assuming that the template on the previous slide is named 'news.blade.php' we can do the following:
  29. Layouts <html><body> <header>Site header goes here!</header> <div id="content"> @yield('content') </div>

    <footer>Site footer goes here!</footer> </body></html> @extends('layout') @section('content') <p>Welcome to the website!</p> @stop layout.blade.php home.blade.php
  30. A quick word on dependencies A dependency is when one

    component (typically an object) relies on another for its operation. Dependencies should be passed (injected) into an object via its constructor or setter methods and not instantiated inside it. Directly instantiating dependencies is considered bad practise as it reduces scalability and flexibility, plus it makes objects difficult to test in isolation.
  31. Dependency examples class Computer { protected $processor; public function __construct()

    { $this->processor = new Processor\Intel\i7(); } } class Computer { protected $processor; public function __construct(ProcessorInterface $processor) { $this->processor = $processor; } } Bad Good
  32. "In software engineering, inversion of control (IoC) is a programming

    technique, expressed here in terms of object-oriented programming, in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis." - Wikipedia So... IoC?
  33. Forget the jargon! App::bind('shopping_basket', function($app) { return new ShoppingBasket( new

    Customer(), new DeliveryService\ParcelForce() ); }); The IoC container is a way of automatically passing dependencies into your objects and/or storing them for later retrieval. $shoppingBasket = App::make('shopping_basket');
  34. Singletons App::singleton('user_session', function($app) { return new UserSession($_SESSION['REMOTE_ADDR']); }); We can

    treat the IoC container as a registry, initialising objects once and returning them on subsequent calls. // First call to App::make() creates the object... $userSession = App::make('user_session'); ! // Second call to App::Make() just fetches it... $sameUserSession = App::make('user_session');
  35. IoC automatic resolution class Computer { protected $processor; public function

    __construct(ProcessorInterface $processor) { $this->processor = $processor; } } If you type-hint the dependencies passed into a constructor then Laravel can do the rest! $computer = App::make('Computer'); // Has i7 processor! App::bind('ProcessorInterface', 'Processor\Intel\i7');
  36. IoC container + Facades = Laravel The static classes used

    to control Laravel are known as Facades. Facades are nothing more than wrappers to the IoC container. Therefore, every time you use a Facade such as DB, Config, View, Route, etc, you are creating and/or fetching a pre- registered object! You can easily create your own application-specific IoC bindings and Facades.
  37. Further Resources Website and documentation: http://www.laravel.com GitHub: http://www.github.com/laravel/framework Laravel Ins

    and Outs: http://laravel.io Laracasts: http://www.laracasts.com Laravel Cheat Sheet: http://cheats.jesse-obrien.ca Leanpub: http://www.leanpub.com Twitter: @laravel, @taylorotwell, @jeffrey_way
  38. Thanks for watching! Email: [email protected] Twitter: @DaGrFr LinkedIn: http://linkedin.com/in/ dgframe

    Web: http://31interactive.com PHPBelfast: http://phpbelfast.com and on Twitter at @PHPBelfast