WordPress Sage Singleton Service in blade template
WordPress Sage Singleton Service in blade template
I'm starting to develop a Wordpress theme with DDEV + Bedrock + Sage.
I have some issues using singleton classes in my blade templates.
This is my code so far to wire things together:
Singleton Service which should be used anywhere in the Project's Logic
final class TestService
{
public static string $name = "TestService";
private static ?TestService $instance = null;
public static function getInstance(): TestService
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
}
private function __clone()
{
}
public function __wakeup()
{
throw new Exception("Cannot unserialize singleton");
}
public function testMethod()
{
return true;
}
}
Service provider to make the service available
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Services\TestService;
class TestServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
// Register services in ServiceProviderOne
$this->app->singleton("TestService", function () {
return TestService::getInstance();
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
Blade page template which should use the service for some logic and display content accordingly
@php
$testService = app("TestService");
$isTest = $testService->testMethod();
@endphp
@extends('layouts.app')
@section('content')
@while(have_posts()) @php(the_post())
@includeFirst(['partials.content-page', 'partials.content'])
@endwhile
@endsection
But the result now is the following error
Target class [TestService] does not exist. (View: /var/www/html/web/app/themes/theme/resources/views/test-page.blade.php)
Is my setup with the singleton and provider wrong? Did I miss some config?
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand