Symfony 4中Sonata Seo Bundle安装后启动报致命错误求助
Hey there, let's get this sorted out quickly! That error pops up because Symfony 4+ defaults all services to private—you can't just yank them directly from the container anymore, which is exactly what your code was doing with sonata.seo.page. Here are the two main ways to fix this:
1. Use Dependency Injection (Recommended)
This is Symfony's modern best practice, and it's cleaner and more maintainable long-term. Instead of grabbing the service from the container manually, inject it directly into the class that needs it (like a controller or custom service).
Example: Constructor Injection in a Controller
// src/Controller/YourController.php namespace App\Controller; use Sonata\SeoBundle\Seo\SeoPageInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class YourController extends AbstractController { private $seoPage; // Inject the SeoPageInterface via the class constructor public function __construct(SeoPageInterface $seoPage) { $this->seoPage = $seoPage; } public function yourAction() { // Now you can use the service normally $this->seoPage->setTitle('My Awesome Page Title'); $this->seoPage->addMeta('name', 'keywords', 'symfony, sonata, seo'); // ... rest of your action logic } }
Symfony will automatically handle wiring up the service for you—no extra configuration needed here!
2. Force the Service to Be Public (Not Recommended)
If you're working with legacy code or have a specific temporary need to fetch the service directly from the container, you can mark sonata.seo.page as public in your services.yaml:
# config/services.yaml services: sonata.seo.page: public: true
Just keep in mind this goes against Symfony's best practices—private services are safer and help with container optimization. Use this only as a short-term fix if you can't refactor to use dependency injection right away.
Bonus: Using Sonata SEO in Twig
If you're trying to use the SEO service in templates, you don't need to inject anything at all! Sonata SEO Bundle provides built-in Twig functions you can use directly:
<title>{{ sonata_seo_title() }}</title> <meta name="description" content="{{ sonata_seo_description() }}"> <meta name="keywords" content="{{ sonata_seo_keywords() }}">
That should resolve the fatal error and get your app running smoothly again.
内容的提问来源于stack exchange,提问作者M. Galardi

