Files
lucent-laravel/docs/Website Setup.md
2023-10-31 23:21:29 +02:00

2.7 KiB

Website Setup

This is an opinionated website setup. It's irrelevant to both Lucent and Laravel. It is just the way I like to organize everything.

Summary

  • Create a Lucent folder with Schemas, Image Filters and Pages
  • Pages are similar to controllers, but will also get used to statically generate the website
  • A Context singleton class that acts as a container for global state
  • A middleware to initiate the Context class and set the application state for the request
  • Some helper functions to make our life easier

Context Class

<?php namespace App\Lucent;

class Context
{
    public string $website = "";
    public string $title;
    public string $description = "";
    public string $url = "";
    public string $mode = "static";
    public string $locale = "el";
    public array $data = [];
    public array $locales = ["el","en"];

    protected array $pages = [
        "homepage" => Homepage::class,
    ];
    
    public function __construct(
        public Application $app,
        public Query $query
        ){}

    public function render(string $pageName, ...$args): string
    {
        $page = $this->app->make($this->pages[$pageName]);
        return $page->render(...$args);
    }

    public function getTitle()
    {
    return empty($this->title) ?  $this->website : $this->title . " | " . $this->website;
    }

    public function getFullUrl(string $path = "")
    {
        return config("app.url") . $this->generateLocaleUrl($path, $this->locale);
    }

    public function localeUrl(string $path = ""): string
    {
        return $this->generateLocaleUrl($path, $this->locale);
    }

    public function switchLocale(string $locale, $path = ""): string
    {
        return $this->generateLocaleUrl($path, $locale);
    }

    private function generateLocaleUrl(string $path, string $locale): string
    {
        if ($this->mode ==  "preview") {
            return config("app.url") . "/preview/" . $locale . "/" . trim($path, "/");
        }
        return config("app.url") . "/" . $locale . "/" . trim($path, "/");
    }
}

Add this class to AppServiceProvider as a singleton

 $this->app->singleton(Context::class);

Context Middleware

<?php namespace App\Http\Middleware;

class Context
{
    public function __construct(public Context $context){}

    public function handle(Request $request, Closure $next, string $mode = "static"): Response
    {
        $this->context->locale = $request->route("locale");
        App::setLocale($this->meta->locale);
        $this->context->mode = $mode;
        $this->context->loadData();
        return $next($request);
    }
}

Add the middleware inside the HTTP Kernel file.