2011-05-31 209 views
6

我想知道是否有正確的方法來檢查依賴關係。依賴關係Symfony2

例如我有NewsBundle。現在我必須檢查是否有CommentBundle。如果有的話,它應該執行更多的代碼。

有什麼建議嗎?

回答

3

您可以在每個bundle應具有的主Bundle類上使用class_exists。

例如:

if (class_exists('Acme\CommentBundle\AcmeCommentBundle')) 
{ 
    // Bundle exists and is loaded by AppKernel... 
} 
+0

尊敬的@markymark,你確定這會給你正確的結果嗎?想象一下情況:捆綁文件存在於文件系統中,但沒有在'AppKernel'中註冊(意味着捆綁的路由既沒有加載服務)。 class_exists('Some \ Name \ Space \ Class')是否會嘗試自動加載類,即使它沒有被註冊到bundle中?我想知道你對此有何看法? HTH – 2014-06-26 14:48:24

24

除了markymark的回答,您可以檢查是否特定服務從控制器存在(或任何其他容器感知代碼)與下面的代碼片段:

if ($this->container->has('foo_service.alias')) 
{ 
    // service is loaded and usable 
} 

如果您不確定給定服務的確切別名,或僅僅是踢腿和咯咯,您可以運行控制檯命令php app/console container:debug查看註冊到容器的所有服務。

+3

+1,您的回答對我而言與上述一樣更加清晰和正確。最好是要求服務 - 而不是捆綁。 – Besnik 2012-09-18 15:15:16

0

Kernel類包含一個幫助程序方法列表,用於檢查某個類是活動包的一部分,還是註冊了一個包。

public BundleInterface[] getBundles() 
    Gets the registered bundle instances. 

public bool isClassInActiveBundle(string $class) 
    Checks if a given class name belongs to an active bundle.