Web Frameworks [OGI06i]

01. Laravel Intro & Config

Before we start …

01.1
Laravel: what to expect

Recap: Frameworks

  • Framework > Library
    • Defines a structure to follow
    • Your project must follow that structure
    • Internally, a framework will most likely contain/use a library
  • PHP frameworks are
    • assisting you in general web application development
    • providing libraries for commonly used functions
    • cutting down the number of lines of repetitive code
    • speeding up the development process
    • resulting in more standardized hence more stable and secure code
    • often MVC

2 Types of Frameworks

  • Microframework
    • Light-weight, extensible, fast
    • Typically: a router connected to an extensible skeleton (where you need to plug and install other services)
    • Examples: Slim, Lumen, Flight
  • Full-featured frameworks
    • Typically: a full-stack (enterprise) MVC framework supporting templating, caching, ORM, security, authentication, forms, …
    • Examples: Symfony, Laravel, Zend, Nette, CodeIgniter, YII, PHPixie

Laravel

  • °2011 by Taylor Otwell
  • Full-featured PHP Framework for the development of web applications and web APIs
    • Model–View–Controller (MVC) pattern
    • A huge number of built-in features
      • Routing
      • Views and Template engine (Blade)
      • DB-related: ORM (Eloquent), Query Builder, Migrations, …
      • Simple authentication
      • Queues, Logging, …
      • Unit testing
    • Emphasis on beautiful code (through syntactic sugar)
    • Artisan CLI
      • Example usages: generate classes, clear cache

Where to start …?

  • Laravel is huge and still growing ⟶ we'll start with the framework basics
  • How does Laravel combine with front-end development?
    There are multiple options (docs, with vue):
    1. Server-side rendering (SSR): Laravel with oldskool HTML template rendering (and some JS) in Blade
    2. Decoupled: Laravel Web API project and front-end project
    3. Integrated development: use Laravel's Asset Building (Vite) and load it from Blade
    4. Develop SPAs using server-side patterns with packages like Inertia.js or Livewire
    ⟶ we'll stick with 1 & 2

Prerequisites

  • You should remember
    • how to work with Docker, git and composer
    • PHP: control structures and object orientation
    • our rules on URL Design
    • the main principles of HTTP (request/response), forms (persistence/form checking), cookies, sessions, …
  • You'd better forget
    • many low-level HTTP-/file-related PHP constructs such as header('Location: /');, $_GET, $_POST, setcookie();, $_COOKIE, session_start();, http_response_code();, move_uploaded_file();, __DIR__, $_ENV, …
    • about solving your problems with arrays 😲

Laravel Programming …

… might feel like handling black boxes

But after a while, you will learn to dig into / intervene in them.

Many of the functional Laravel code is located somewhere in the vendor folder, which of course you should not modify (not on git). Often, the code is organized into traits of which you can override the methods in your own project.

PHP Recaps and Updates

  • Traits
    • Reducing some limitations of single inheritance
    • Define a a set of methods via the trait keyword e.g. trait Example {
    • Reuse this set of methods by putting use Example; inside the class
  • The behaviour of inaccessible properties (->) with property overloading
    • __set() is called when writing to non-existing properties with ->
    • __get() is called when reading non-existing properties with ->
  • Namespaces
    • Define a class Baz within a namespace: start with namespace Ikdoeict\Demo;
    • Within Baz: refer to other classes of the same namespace: just by their base name
    • Refer to classes outside the namespace: first import the class by use Ikdoeict\Base\Model; and just use Model after that
  • We'll be using PHP 8.5. Let's have a look what has changed →

Course Outline

  • Laravel basics: configuration, routing, Request/Response, Blade (templates)
  • MVC: Query Builder, Eloquent (ORM), Controllers, Migrations/Seeders
  • Forms with Validation, File Uploads, Filtering, Pagination
  • Web APIs with Eloquent API Resources
  • Middleware, authentication and authorization

01.2
Getting started with Laravel

Local Dev Env for Laravel?

  • Many options for local development environments with Laravel
    • Native bundle
    • Vagrant*-based (*outdated)
    • Docker-based
      • Laravel Sail: official dev env, set-up from within a Laravel library
      • Laradock: a swiss knife Docker environment (consisting of > 60 Docker images of high quality), to be cloned once for all your web projects
      • your own reproducible docker-compose environment
        → what we choose in this course
        → let's have a look

Laravel on Docker for Windows

Important remark

  • Laravel is too slow on Docker Desktop for Windows (WSL2)
    • when bind-mounting your Laravel project in a Docker Container
    • because WSL2 has poor filesystem performance
      ⟶ each PHP file access introducing some serious time delay (e.g. 100ms)
      ⟶ an HTTP request to a Laravel project results into many PHP file accesses
      ⟶ HTTP response delayed for seconds
  • You cannot test/learn Laravel efficiently that way. No you can't!
  • Solution: enable Docker integration with WSL2 distro & store your project in the Linux filesystem of WSL2
    • access through \\wsl$ in Explorer and CLI through your distro
    • IDEs know ± how to handle this
    • see Handleiding Docker-WSL2-Ubuntu.pdf on Toledo

Composer-based Installation

  • Installable via Composer
    $ composer create-project laravel/laravel <path> ^12.0
    • <path> is the actual directory where you want to install Laravel, e.g. . = current directory
    • ^12.0 tag is optional - semantic versioning: everything within 12.*.* range is backward compatible
    • composer create-project is the equivalent of git clone + composer install. So:
      • It downloads the whole project structure including folders, PHP-files, an .htaccess file and a rather complex composer.json file.
      • Next, all dependencies are installed in the vendor folder and composer.lock is generated.
      • So: you start with an already ± working project
  • Nevertheless, only laravel new projectname, is the officially documented way to install Laravel through an interactive menu. You cannot specify the Laravel version number!

Project Structure (1)

(Laravel docs)

  • public/ — Public files
    • the document root of your web server points to this folder!
    • index.php — Request Entry Point - please don't touch it
    • add your assets: css/ & js/ & img/ & files/ &
    • .htaccess (or alike), favicon.ico, robots.txt
  • routes/ — Routes
    • web.php — Your web routes
    • api.php — Your (stateless) API routes (requires php artisan install:api)
    • console.php — Your Artisan console routes
    • channels.php — Your channels for event broadcasting (websockets; requires php artisan install:broadcasting)
  • app/PSR-4 classes of your application — 3…13 subfolders e.g.
    • Console/ — Your Artisan commands
    • Http/ — Your controllers and middleware
    • You create the classes with Artisan, which might add subfolders
Note: Make sure only the contents of public/ is accessible over HTTP(s)!

Project Structure (2)

  • bootstrap/ — Bootstrap and autoloading
  • config/ — Configuration files
  • database/ — Database migration and seeds
  • lang/ — Language files (only when you publish them by Artisan)
  • resources/ — Raw assets (to be compiled) such as templates and localization files
  • storage/ — All kinds of generated files: logs, transpiled templates, caches, …
  • tests/ — Automated tests (PHPUnit or Pest)
  • vendor/(as created by Composer)
  • .env — Environment configuration: see next slides
  • .env.example — Example environment configuration: see next slides
  • .gitignore(already configured)
  • artisan — supports Artisan CLI
  • composer.json & composer.lock
  • some Vite-related, PhpUnit-related and editor-related config files

The Request Lifecycle

How Laravel works
(Laravel docs)

  • Webserver hands over the request to public/index.php
  • It loads Composer's autoloader
  • It retrieves an instance of the application service container from the bootstrap/app.php script
  • Next, the request is handled by the HTTP Kernel
    • Bootstrapping includes calling register and boot on the service providers defined in bootstrap/providers.php
    • Request passes the middleware e.g. session handling, CSRF token
    • Next, the request is dispatched to the router

Artisan Console

  • Functions: clear caches, generate classes, …
  • Available commands and help
    $ php artisan list
  • Help on a specific command
    $ php artisan help serve
  • You can extend Artisan with your own commands
Run php artisan from the same environment as the webserver

Need help?!

01.3
Next Step: Configuration

Pay attention!

Permissions and Application Key

  • Directory permissions
    • storage/ and bootstrap/cache writable by web server (associated account)
  • Application key (= IMPORTANT)
    • a random and secret key, used for session security and encryption
    • location: .env environment file
    • assigned for you by the Composer/Laravel installer (not when you copied the project or alike)
    • if necessary, generate with
      $ php artisan key:generate

The config Folder

  • Additional configuration
    • config/app.php — Main settings, locale, timezone, automatically loaded service providers, …
    • config/database.php — Database connection configurations
    • 8 other config files e.g. config/cache.php, config/session.php, …
    • 5 more config files (e.g. config/cors.php) can be generated by php artisan config:publish
    • format: one big (nested) array of key-value pairs of settings e.g.
      'charset' => 'utf8mb4',

The env() Function

  • Including environment variables in the config/*.php files
    • the env() function gets the value of an environment variable or returns a default value
      • Example without default value from config/app.php:
        'key' => env('APP_KEY'),
      • Example with default value from config/database.php:
        'password' => env('DB_PASSWORD', 'Azerty123'),
    • Environment variables must/can be set in the .env file e.g.
      APP_KEY=base64:DBHbcyBbq0pBarhWVn0S8bYMqt9IV9EhXhthcyeioKw=
      DB_PASSWORD=secret
    • This is the mechanism behind the Environment Configuration

The Environment Configuration

  • In short: the .env file must/can be used to override settings in the config files
  • Why? local/dev/testing/production configurations may be different w.r.t. DB host, personal keys, Facebook Dev Credentials, e-mail component, …
  • How to use craft
    • Have some configuration in config/*.php
    • Override parts of it with local settings in .env
    • .env must be kept out of version control (git → .gitignore).
      It contains sensitive information: the application key is always in .env
    • Installation instructions in README.md: if necessary, put .env's non-sensitive lines into .env.example and suggest to cp .env.example .env in the installation instructions

Example: database config (1)

config/database.php
<?php

return [
    …
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [
        'sqlite' => [
            …
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'db009.my-hosting-company.be'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'events'),
            'username' => env('DB_USERNAME', 'production'),
            'password' => env('DB_PASSWORD', 'Azerty123'),
            'charset' => 'utf8mb4',
			…

Example: database config (2)

.env
APP_NAME=Concert Guide
APP_ENV=local
APP_KEY=base64:WB2aLCAIUgFJCZbbg/KIA6M4Hum1bsz/s+o8hxbeW68=
APP_DEBUG=true
APP_TIMEZONE=UTC
APP_URL=http://localhost:8080

...

DB_CONNECTION=sqlite
  • You can ...
    • also override parts of the connection config (e.g. just the encoding or password)
    • remove DB_CONNECTION=sqlite if you agree with the default connection in config/database.php
  • but you cannot delete .env

Some more configuration troubleshooting

  • For a quick overview of your configuration
    $ php artisan about
  • To explore some config values in detail
    $ php artisan config:show database
  • With encrypting and decrypting .env files, .env may be safely added to git
Run php artisan from the same environment as the webserver

Installation Manual

    colored text = with Docker on Windows

  • Installing a fresh Laravel project
    1. Create a new empty repo on gitlab
    2. git clone <repo-url> inside the WSL2-Linux filesystem
    3. Add /docker-compose.yml /.gitignore /docker/Dockerfile /docker/php.ini (/docker/dump.sql) /app
      Keep /app empty. /app/public will become the document root of the web container later on
    4. docker-compose up
      docker-compose exec -u 1000:1000 php-web bash
      $ composer create-project laravel/laravel . ^12.0
      $ chmod -R 777 storage bootstrap/cache
    5. Craft .env (APP_*, DB_* and SESSION_DRIVER=file) and config/*.php
    6. If necessary: copy the non-sensitive parts of .env to .env.example
    7. git add .   git commit -m "Adding initial Laravel project"   git push
  • Installing an already existing Laravel project
    1. git clone <repo-url> inside the WSL2-Linux filesystem
    2. docker-compose up
      docker-compose exec -u 1000:1000 php-web bash
      $ composer install
      $ cp .env.example .env
      $ php artisan key:generate
      $ chmod -R 777 storage bootstrap/cache

Questions?

Sources