如何访问捆绑器构造器中的服务?我试图创建一个系统,其中一个主题包可以自动本身的主题服务注册,见下文(比较简单的解决越好)小例子:Symfony:无法访问捆绑构造器中的服务
<?php
namespace Organization\Theme\BasicBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class ThemeBasicBundle extends Bundle
{
public function __construct() {
$themes = $this->get('organization.themes');
$themes->register(new Organization\Theme\BasicBundle\Entity\Theme(__DIR__));
}
}
然而,这 - $>获取不起作用,这可能是因为不能保证所有捆绑包都已经被注册了,是否有任何捆绑注册“钩子”可以用来代替?是否有任何特殊的方法名称可以添加到捆绑类中,并在所有捆绑包实例化后执行?
服务类看起来是这样的:
<?php
namespace Organization\Theme\BasicBundle;
use Organization\Theme\BasicBundle\Entity\Theme;
class ThemeService
{
private $themes = array();
public function register(Theme $theme) {
$name = $theme->getName();
if (in_array($name, array_keys($this->themes))) {
throw new Exception('Unable to register theme, another theme with the same name ('.$name.') is already registered.');
}
$this->themes[$name] = $theme;
}
public function findAll() {
return $this->themes;
}
public function findByName(string $name) {
$result = null;
foreach($this->themes as $theme) {
if ($theme->getName() === $name) {
$result = $theme;
}
}
return $result;
}
}
捆绑::启动被执行。你的问题是哪种答案。但是,在构建阶段执行此操作是正确的方法。 – Cerad