Skip to content

Getting a Service Instance

There are three ways to get an instance of the WeasyPrint service class.

Option 1. Factory Contract

This contract may either be used in dependency injection, or via the global app() or resolve() helper functions.

Dependency Injection:

php
use WeasyPrint\Contracts\Factory;

class GeneratePDF
{
  public function __invoke(Factory $weasyprint)
  {
    // You now have access to a WeasyPrint instance named $weasyprint.
    $weasyprint->prepareSource('<p>WeasyPrint rocks!</p>');
  }
}

Global Helpers:

php
use WeasyPrint\Contracts\Factory;

$weasyprint = app(Factory::class); // or resolve(Factory::class)

// You now have access to a WeasyPrint instance named $weasyprint.
$weasyprint->prepareSource('<p>WeasyPrint rocks!</p>');

Option 2. Service Helper

If you do not want to use dependency injection, and you do not want to use the app() or resolve() helpers directly, you can use the service instance helper instead.

php
use WeasyPrint\Service;

$weasyprint = Service::instance();
$weasyprint->prepareSource('<p>WeasyPrint rocks!</p>');

This has the same effect as calling one the global helpers, but provides better type-safety and, as a result, IDE support.

Option 3. Facade

Similar to the other options, using the Facade will give you an instance of the WeasyPrint service singleton. The Facade resolves to the Factory contract which, in turn, provides you with the singleton.

php
use WeasyPrint\Facade as WeasyPrint;

$source = '<p>WeasyPrint rocks!</p>';
$service = WeasyPrint::prepareSource($source);

Documentation Note

For the sake of simplicity, the facade option will be used throughout the remainder of this documentation.

Released under the ISC License.