# Symfony quickstart

> A Symfony website that shows every CMS Orbit page at its own address with Twig templates, previews drafts in the editor and clears cached pages by tag when editors publish.

Source: https://docs.bifrostorbit.com/cms/developers/quickstart-symfony/

This guide builds a Symfony website for Northwilds that reads its pages from CMS Orbit with the PHP SDK, `bifrost-orbit/cms-sdk`. Every page an editor publishes appears at its own address, each component is drawn by a Twig template, editors see their drafts in the live preview, and a signed webhook clears only the cached pages that changed.

Tested with Symfony 8.1, Twig 3.30, PHP 8.5, Composer 2.10 and `bifrost-orbit/cms-sdk` 0.2.0.

Prefer to start from a working project? Use the starter: [bifrost-orbit/cms-starter-symfony](https://github.com/bifrost-orbit/cms-starter-symfony), the finished code of this guide.

## Before you start

You need:

- **PHP 8.4 or later and Composer**, for Symfony 8. The SDK itself needs PHP 8.1 or later.
- **A CMS Orbit space** with at least one published page, such as the home page at `/`.
- **Two keys** from **Configuration › API keys**: a public `cms_pk_` key for published content and a secret `cms_sk_` key with **Read drafts** on, from Staging. Step 4 of [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) shows how to create them.
- **The API address and the region key.** The address is `https://api.bifrostorbit.com/cms`. The region key, such as `germany`, is in **Configuration › Environments**. See step 3 of [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/).

## 1. Create the project

```bash
composer create-project symfony/skeleton northwilds
cd northwilds
```

## 2. Install the SDK

Install it together with Twig:

```bash
composer require twig bifrost-orbit/cms-sdk:^0.2
```

## 3. Add the settings

Keep the keys in `.env.local`, which Symfony leaves out of Git:

```bash
# .env.local
CMS_API_URL=https://api.bifrostorbit.com/cms
CMS_PUBLIC_KEY=cms_pk_…
CMS_PREVIEW_KEY=cms_sk_…
CMS_WEBHOOK_SECRET=whsec_…
CMS_DEFAULT_REGION=germany
```

`CMS_WEBHOOK_SECRET` comes in step 8. On your server, set them as environment variables instead.

## 4. Create the client

Add the client to the end of `services` in `config/services.yaml`:

```yaml
# config/services.yaml
    BifrostOrbit\Cms\Client:
        arguments:
            $apiKey: '%env(CMS_PUBLIC_KEY)%'
            $baseUrl: '%env(CMS_API_URL)%'
            $previewKey: '%env(default::CMS_PREVIEW_KEY)%'
            $defaultRegion: '%env(default::CMS_DEFAULT_REGION)%'
```

Give CMS answers their own cache pool with tags, so the webhook can clear only what changed. Replace `config/packages/cache.yaml` with:

```yaml
# config/packages/cache.yaml
framework:
    cache:
        pools:
            cms.cache:
                adapter: cache.adapter.filesystem
                tags: true
```

Symfony passes the pool to any argument named `TagAwareCacheInterface $cmsCache`.

## 5. Show a page

One route with a low priority catches every address that no other route takes:

```php
// src/Controller/PageController.php
<?php

namespace App\Controller;

use BifrostOrbit\Cms\CacheTags;
use BifrostOrbit\Cms\Client;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

final class PageController extends AbstractController
{
    #[Route('/{path}', name: 'cms_page', requirements: ['path' => '.*'], methods: ['GET'], priority: -100)]
    public function show(Client $cms, TagAwareCacheInterface $cmsCache, string $path = ''): Response
    {
        $path = '/' . $path;
        $tag = CacheTags::page((string) $cms->defaultRegion, $path);
        $result = $cmsCache->get(CacheTags::safe($tag), function (ItemInterface $item) use ($cms, $path, $tag) {
            $item->expiresAfter(60);
            $item->tag(CacheTags::safeAll([CacheTags::ALL, $tag]));

            return $cms->resolve($path);
        });

        $response = match ($result['kind']) {
            'redirect' => new RedirectResponse($result['to'], $result['status']),
            'gone' => throw new GoneHttpException(),
            'notFound' => throw new NotFoundHttpException(),
            'page' => $this->render('page.html.twig', ['page' => $result['page'], 'preview' => false]),
        };

        return $response->setPublic()->setMaxAge(60);
    }
}
```

`resolve` says what the address is. A moved page redirects with the status the editor chose, a deleted one answers `410`, and an unknown address answers `404`. Each answer is cached for 60 seconds under the same tags as the JavaScript SDK, such as `cms:page:germany:/pricing`, and the page's tag is its key too. Symfony does not allow `:` or `/` in cache keys and tags, so `CacheTags::safe` and `CacheTags::safeAll` encode them, as `cms%3Apage%3Agermany%3A%2Fpricing`.

A Twig extension gives templates the page's `<head>` tags, the components and the preview bridge:

```php
// src/Twig/CmsExtension.php
<?php

namespace App\Twig;

use BifrostOrbit\Cms\BlockRenderer;
use BifrostOrbit\Cms\Client;
use BifrostOrbit\Cms\Preview;
use BifrostOrbit\Cms\Seo;
use Twig\Attribute\AsTwigFunction;
use Twig\Environment;

final class CmsExtension
{
    private const TEMPLATES = [];

    public function __construct(private readonly Client $cms)
    {
    }

    #[AsTwigFunction('cms_blocks', needsEnvironment: true, isSafe: ['html'])]
    public function blocks(Environment $twig, ?iterable $blocks): string
    {
        return $this->renderer($twig)->render($blocks ?? []);
    }

    #[AsTwigFunction('cms_block', needsEnvironment: true, isSafe: ['html'])]
    public function block(Environment $twig, ?array $block): string
    {
        return $this->renderer($twig)->renderOne($block);
    }

    #[AsTwigFunction('cms_head', isSafe: ['html'])]
    public function head(array $page): string
    {
        return Seo::headTags($page) . Seo::jsonLd($page);
    }

    #[AsTwigFunction('cms_bridge', isSafe: ['html'])]
    public function bridge(): string
    {
        return Preview::bridgeScript($this->cms);
    }

    private function renderer(Environment $twig): BlockRenderer
    {
        return new BlockRenderer(
            array_map(fn (string $template) => fn (array $block) => $twig->render($template, ['block' => $block]), self::TEMPLATES),
            fn (array $block) => $twig->render('blocks/unknown.html.twig', ['block' => $block]),
        );
    }
}
```

```twig
{# templates/page.html.twig #}
<!DOCTYPE html>
<html lang="{{ page.locale }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    {{ cms_head(page) }}
</head>
<body>
    <main>
        {{ cms_blocks(page.components) }}
    </main>
    {% if preview %}
        {{ cms_bridge() }}
    {% endif %}
</body>
</html>
```

```twig
{# templates/blocks/unknown.html.twig #}
{% if app.debug %}
    <section data-cms-id="{{ block.id }}">
        <p>No template for the {{ block.type }} component yet.</p>
    </section>
{% endif %}
```

`cms_head` prints the page's title, description, canonical address, share tags and structured data. The fallback names a component without a template while debug is on, and prints nothing on the live website.

Run `php -S localhost:8000 -t public` and open `http://localhost:8000`. The page has its title, and each component shows "No template for the hero component yet". An address that is not in CMS Orbit, such as `/no-such-page`, answers `404`.

## 6. Write and register components

Each component arrives with `id`, `type`, `fields` and `children`. Here are templates for a hero with two buttons and a feature grid with its items. Your space's components and fields may have other names: see them in **Configuration › Components**.

```twig
{# templates/blocks/hero.html.twig #}
{% set f = block.fields %}
<section class="hero" data-cms-id="{{ block.id }}">
    {% if f.eyebrow is not empty %}
        <p class="eyebrow">{{ f.eyebrow }}</p>
    {% endif %}
    <h1>{{ f.heading }}</h1>
    {{ f.description|raw }}
    <div class="actions">
        {{ cms_block(f.primaryAction ?? null) }}
        {{ cms_block(f.secondaryAction ?? null) }}
    </div>
</section>
```

```twig
{# templates/blocks/action.html.twig #}
{% set f = block.fields %}
<a class="button {{ f.style ?? '' }}" href="{{ f.link.href ?? '#' }}" data-cms-id="{{ block.id }}">
    {{ f.label }}
</a>
```

```twig
{# templates/blocks/feature_grid.html.twig #}
{% set f = block.fields %}
<section class="feature-grid" data-cms-id="{{ block.id }}">
    <h2>{{ f.heading }}</h2>
    {% if f.intro is not empty %}
        <p>{{ f.intro }}</p>
    {% endif %}
    <div class="grid">
        {{ cms_blocks(block.children.items ?? []) }}
    </div>
</section>
```

```twig
{# templates/blocks/feature_item.html.twig #}
{% set f = block.fields %}
<article data-cms-id="{{ block.id }}">
    <h3>{{ f.title }}</h3>
    <p>{{ f.body }}</p>
    {% if f.link.href is defined and f.link.href is not empty %}
        <a href="{{ f.link.href }}">Read more</a>
    {% endif %}
</article>
```

Rich text, such as the hero's `description`, arrives as HTML, so print it with `|raw`. Twig escapes everything else. A block in a single slot, such as a button, is on its field, so `cms_block` draws it. `cms_blocks` draws a list, such as the grid's items in `block.children.items`.

Register the templates by component key. In `src/Twig/CmsExtension.php`, replace the `TEMPLATES` constant with:

```php
private const TEMPLATES = [
    'hero' => 'blocks/hero.html.twig',
    'featureGrid' => 'blocks/feature_grid.html.twig',
    'featureItem' => 'blocks/feature_item.html.twig',
    'action' => 'blocks/action.html.twig',
];
```

Reload the page: the hero is drawn by your template, and the fallback names the components still to write.

## 7. Preview drafts in the editor

The editor opens your website at the space's **Preview URL** followed by the page's address and `?preview=<token>`. The controller checks the token, sets a cookie and sends the editor to the page. While the cookie is there, it reads drafts with the secret key, never caches them, and `page.html.twig` adds the bridge script. Replace the controller with:

```php
// src/Controller/PageController.php
<?php

namespace App\Controller;

use BifrostOrbit\Cms\CacheTags;
use BifrostOrbit\Cms\Client;
use BifrostOrbit\Cms\Preview;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\GoneHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

final class PageController extends AbstractController
{
    #[Route('/{path}', name: 'cms_page', requirements: ['path' => '.*'], methods: ['GET'], priority: -100)]
    public function show(Request $request, Client $cms, TagAwareCacheInterface $cmsCache, string $path = ''): Response
    {
        $path = '/' . $path;

        $token = $request->query->getString('preview');
        if ($token !== '') {
            $claims = $cms->verifyPreviewToken($token);
            if ($claims === null) {
                return new Response('That preview link is invalid or has expired', Response::HTTP_UNAUTHORIZED);
            }
            $response = new RedirectResponse(Preview::redirectPath($path, $claims));
            $response->headers->setCookie(Cookie::create('cms_preview', '1', secure: true, sameSite: Cookie::SAMESITE_NONE));

            return $response;
        }

        $preview = $request->cookies->get('cms_preview') === '1';
        $tag = CacheTags::page((string) $cms->defaultRegion, $path);
        $result = $preview
            ? $cms->resolve($path, ['preview' => true])
            : $cmsCache->get(CacheTags::safe($tag), function (ItemInterface $item) use ($cms, $path, $tag) {
                $item->expiresAfter(60);
                $item->tag(CacheTags::safeAll([CacheTags::ALL, $tag]));

                return $cms->resolve($path);
            });

        $response = match ($result['kind']) {
            'redirect' => new RedirectResponse($result['to'], $result['status']),
            'gone' => throw new GoneHttpException(),
            'notFound' => throw new NotFoundHttpException(),
            'page' => $this->render('page.html.twig', ['page' => $result['page'], 'preview' => $preview]),
        };

        return $preview ? $response->setPrivate()->setMaxAge(0) : $response->setPublic()->setMaxAge(60);
    }
}
```

`Preview::redirectPath` only ever sends the editor to an address on your own website. The bridge lets editors click a component to select it, through the `data-cms-id` on each template's outer element, and reloads the preview after each save.

The cookie is `Secure` with `SameSite=None`, so the browser keeps it inside the editor's frame. Serve the preview website over `https`, and set its address as the **Preview URL** in the space's **Settings**. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).

## 8. Refresh when editors publish

Create a webhook in **Configuration › Webhooks** with the address `https://<your website>/cms-webhook`, and put its secret in `CMS_WEBHOOK_SECRET`. See [Refresh the website when content changes](https://docs.bifrostorbit.com/cms/developers/webhooks/).

```php
// src/Controller/CmsWebhookController.php
<?php

namespace App\Controller;

use BifrostOrbit\Cms\CacheTags;
use BifrostOrbit\Cms\Webhook;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

final class CmsWebhookController
{
    #[Route('/cms-webhook', name: 'cms_webhook', methods: ['POST'])]
    public function __invoke(
        Request $request,
        TagAwareCacheInterface $cmsCache,
        #[Autowire(env: 'CMS_WEBHOOK_SECRET')] string $secret,
    ): Response {
        $message = Webhook::parse($secret, $request->headers->all(), $request->getContent());

        if ($message === null) {
            return new Response(null, Response::HTTP_UNAUTHORIZED);
        }

        $tags = Webhook::tagsForEvent($message['event'], $message['data']);
        $cmsCache->invalidateTags(CacheTags::safeAll($tags));

        return new Response(null, Response::HTTP_NO_CONTENT);
    }
}
```

`Webhook::parse` checks the signature against the raw body and refuses messages more than five minutes old. `tagsForEvent` names what changed: publishing `/pricing` clears only that page, while a change that can touch every page, such as a shared section or a page moved to a new address, returns `cms` and clears them all. `CacheTags::safeAll` encodes them the same way as the controller did when it stored the pages. A test message from **Send a test** has no tags, so it answers `204` and clears nothing.

A correctly signed message answers `204`, and one with a wrong signature or an old timestamp answers `401`. Use the region's key in `CMS_DEFAULT_REGION`, not its short code, since webhooks name the region by its key. See [Caching and refreshing pages](https://docs.bifrostorbit.com/cms/developers/caching-and-refresh/).

## Next steps

- [The PHP SDK](https://docs.bifrostorbit.com/cms/developers/sdk-php/): every client method, menus, global content, lists, images, errors and tests
- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): fields, images, links, slots and variants
- [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/): what the editor needs from your website
- [Refresh the website when content changes](https://docs.bifrostorbit.com/cms/developers/webhooks/): events and what each one carries
- [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/): show more than one region or language
- [Metadata, sitemaps and robots with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/): sitemaps, robots.txt and structured data
- [Troubleshooting your website](https://docs.bifrostorbit.com/cms/developers/troubleshooting/): when a page, the preview or a webhook does not work
