2011-07-07 26 views
10

Tôi có một gói bộ nạp (LoaderBundle) nên đăng ký các gói khác trong cùng một thư mục.Có thể đăng ký động các gói trong Symfony2 không?

/Acme/LoaderBundle/... 
/Acme/ToBeLoadedBundle1/... 
/Acme/ToBeLoadedBundle2/... 

tôi muốn tránh bằng tay đăng ký mỗi gói mới (trong Acme thư mục) trong AppKernel::registerBundles(). Tốt hơn là tôi muốn một cái gì đó trong LoaderBundle để chạy trên mọi yêu cầu và tự động đăng ký ToBeLoadedBundle1ToBeLoadedBundle2. Có thể không?

+0

Cố gắng tránh sự cần thiết phải làm cho PHP mở thư mục và/hoặc các tập tin stat. Ngay cả với bộ đệm hệ điều hành lớn này là bất lợi cho hiệu suất. Tất nhiên nó có thể khá tiện dụng để phát triển. – PAStheLoD

Trả lời

7

chưa được kiểm tra nhưng bạn có thể thử một cái gì đó giống như

use Symfony\Component\HttpKernel\Kernel; 
use Symfony\Component\Config\Loader\LoaderInterface; 
use Symfony\Component\Finder\Finder; 

class AppKernel extends Kernel 
{ 
    public function registerBundles() 
    { 
     $bundles = array(
      new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), 
      //... default bundles 
     ); 

     if (in_array($this->getEnvironment(), array('dev', 'test'))) { 
      $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); 
      // ... debug and development bundles 
     } 

     $searchPath = __DIR__.'/../src'; 
     $finder  = new Finder(); 
     $finder->files() 
       ->in($searchPath) 
       ->name('*Bundle.php'); 

     foreach ($finder as $file) { 
      $path  = substr($file->getRealpath(), strlen($searchPath) + 1, -4); 
      $parts  = explode('/', $path); 
      $class  = array_pop($parts); 
      $namespace = implode('\\', $parts); 
      $class  = $namespace.'\\'.$class; 
      $bundles[] = new $class(); 
     } 

     return $bundles; 
    } 

    public function registerContainerConfiguration(LoaderInterface $loader) 
    { 
     $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); 
    } 
} 
+0

Cảm ơn. Nó đã dẫn tôi đến giải pháp đúng. Tôi đã không nhận ra rằng tôi có thể làm việc với các lớp học bình thường ngay cả khi các gói chưa được đăng ký. –

-2

Câu trả lời trước đó chứa một sai lầm nhỏ, nơi nó sẽ bao gồm các lớp với a/ở phía trước, đây là mã được cập nhật

foreach ($finder as $file) { 
      $path  = substr($file->getRealpath(), strrpos($file->getRealpath(), "src") + 4); 
      $parts  = explode('/', $path); 
      $class  = array_pop($parts); 
      $namespace = implode('\\', $parts); 
      $class  = $namespace.'\\'.$class; 
      //remove first slash 
      $class = substr($class, 1, -4); 
      $bundles[] = new $class(); 
     } 
Các vấn đề liên quan