DEV Community

Cover image for Using singleton in Wordpress Sage9/10 themes view composers
RomkaCodeSome
RomkaCodeSome

Posted on

Using singleton in Wordpress Sage9/10 themes view composers

A small pro tip for devs who are using WordPress Sage9/10 for theme development. I saw many devs doesn't realize that when you are creating View composer and doing stuff inside it, like calling internal functions or executing SQL, for example:

get_bloginfo('name', 'display')
Enter fullscreen mode Exit fullscreen mode

It will be executed as many times as blade files are involved, for example:

protected static $views = [
    '*',
];
Enter fullscreen mode Exit fullscreen mode

Will execute get_bloginfo() for all blade files.

You should make use of singleton for this, inside ThemeServiceProvider.php register method add:

$this->app->singleton(App::class);
Enter fullscreen mode Exit fullscreen mode

Where App::class is view composer class, from now on, service container will not load this class if it's already loaded.

Top comments (0)