Was this page helpful?

Getting started with Contentful and Symfony

This tutorial will show you how to setup the ContentfulBundle in your Symfony application and how to access you content inside the framework.

Requirements

The ContentfulBundle requires Symfony 3.4 or 4.0 (and higher), and PHP 7.0.

Install using Symfony Flex

This bundle is compatible with Symfony Flex. In order to use it, please enable contrib recipes by executing this command in your project root:

composer config extra.symfony.allow-contrib true

Now require the actual package:

composer require contentful/contentful-bundle

After the package is installed, Symfony Flex will do the following:

  • Copy the default bundle configuration to config/packages/contentful.yaml.
  • Add placeholder environment variables to your .env file.
  • Register the bundle in config/bundles.php.

Install without Symfony Flex

If you're using this bundle with a pre-Flex install of the Symfony framework, follow these steps. First, require the package:

composer require contentful/contentful-bundle

Next you need to enable the Bundle by adding it to your app's kernel in app/AppKernel.php:

public function registerBundles()
{
    return [
        // ...
        new Contentful\ContentfulBundle\ContentfulBundle(),
        // ...
    ];
}

Finally, add the bundle configuration to your app/config/config.yml file:

contentful:
    delivery:
        space: cfexampleapi
        token: b4c0n73n7fu1

Using the client

Regardless of your method of installing the bundle, you now have the services contentful.delivery and contentful.delivery.default_client available. Both pointing to the default client. If you have more than one client configured, or have specified a name, clients will be available in services following this naming scheme: contentful.delivery.{name}_client. A small controller displaying an entry based on an ID in the URL could look like this:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Contentful\Core\Exception\NotFoundException;
use Contentful\Delivery\Client;

class DefaultController extends Controller
{
    /**
     * @Route("/entry/{id}", name="entry.item")
     */
    public function entryAction($id)
    {
        /** @var Client $client */
        $client = $this->get('contentful.delivery');

        try {
            $entry = $client->getEntry($id);
        } catch (NotFoundException $contentfulException) {
            throw new NotFoundHttpException();
        }

        return $this->render('default/entry.html.twig', [
            'entry' => $entry
        ]);
    }
}

To discover how to use the Contentful client, check out the getting started with Contentful and PHP tutorial.

Using the Web Debug Toolbar

The ContentfulBundle integrates with Symfony's Web Debug Toolbar. If the toolbar is shown and there were requests to the Contentful API, there will be a section showing how many requests haven been made against the API.

Clicking on that section will open the Contentful panel in the web profiler.

This view shows you a all requests that were made against one of Contentful's API including how long they took. Clicking on the the "Details" in the last column gives you an overview of the request and response and exceptions thrown by the Contentful SDK.

Configuration options

This bundle supports a variety of configuration options. Regarless of whether your confiuration lives in config/packages/contentful.yaml or app/config/config.yml, here is the full config:

contentful:
    delivery:
        space: SPACE_ID
        token: ACCESS_TOKEN
        # Defaults to "master"
        environment: master
        # Defaults to false, set to true to use the Preview API
        # instead of the Delivery API
        preview: true
        # A locale to be used on all API calls,
        # defaults to null
        default_locale: en-US
        # A URI to be used as a replacement for all API calls,
        # might be useful in a proxy setup, defaults to null
        base_uri: https://cdn.contentful.com
        # The service ID of a custom Guzzle client instance
        http_client: null
        # Set it to true or to a service ID for using a PSR-6 cache
        # pool, for storing content type and environment data locally,
        # defaults to false
        cache: true
        # Set it to true to have the cache pool automatically populate
        # during regular use instead of having to preload it,
        # defaults to false
        cache_auto_warmup: true

The bundle also supports a multi-client configuration mode. The options available for every client are the same as above, but the configuratio hierarchy differs:

contentful:
    delivery:
        default_client: delivery
        clients:
            delivery:
                space: SPACE_ID
                token: DELIVERY_ACCESS_TOKEN
            preview:
                space: SPACE_ID
                token: PREVIEW_ACCESS_TOKEN
                preview: true

To confirm that everything is configured as you wish, execute php bin/console contentful:info in your shell. The output should look like this:

Contentful clients
==================

 --------- ------------------------------------ ---------- -------------- ------------- -----------
  Name      Service                              API        Space          Environment   Cache
 --------- ------------------------------------ ---------- -------------- ------------- -----------
  default   contentful.delivery.default_client   DELIVERY   cfexampleapi   master        cache.app
 --------- ------------------------------------ ---------- -------------- ------------- -----------

Conclusion

Now you should be familiar with the basics of how to use Contentful in a Symfony application. You can find the Bundle on GitHub and Packagist. To get a deeper understanding, read some of our other PHP tutorials. If you find a bug, or have an idea how to further integrate with Symfony, please open an issue on GitHub.