Symfony PHP framework standard service set up pattern for classes and libraries
Symfony standard service set up pattern. Setting up a class to be accessible from any Symfony file is easiest done through the “service container”.
Here is an example of setting up a new service.
//To render a TWIG template from a string
//src/Project/Bundle/CoreBundle/Resources/config/services.yml:
services:
core.twig.string.loader:
class: Twig_Loader_String
core.twig.string:
class: %twig.class%
arguments: ["@core.twig.string.loader", %twig.options%]
You can then call the following to render the template:
$this->container->get('core.twig.string')->render($twig_string, ...);
Simple enough. You may be tempted to just include a file and create a new instance of the class with the \BaseNamespace, but remember your bundles are bundled for a reason and not including external libraries the “Symfony way” may cause you dependency issues and migration issues later.