2017-12-14 4 views
1

내 앱에서 모든 Eloquent 모델의 목록을 얻는 방법을 찾고 싶습니다. 아마도 나는 리플렉션을 사용해야합니다.Laravel에서 모든 Eloquent 모델을 얻는 방법?

여기 제가 시도한 바가 있습니다. 그러나 이것은 작동하지 않습니다. get_declared_classes()

  1. 은 개체가 아닌 문자열 배열을 반환하기 때문에 작동하지 않습니다.
  2. 에는 모델 클래스가 표시되지 않습니다.

.

<?php 
namespace App\Providers; 

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; 

class IdentifierGeneratorServiceProvider extends ServiceProvider 
{ 
    public function boot() 
    { 
     foreach (get_declared_classes() as $class) { 
      if (!($class instanceof Model)) { 
       continue; 
      } 
      // At this point I know that $class is an instance of Illuminate\Database\Eloquent\Model 
      // I should be able to call any method of the Model object 
      // like this $class->getIncrementing(); 
     } 
    } 

    public function register() 
    { 

    } 
} 

답변

0

가변 변수/가변 인수를 사용할 수 있습니다.

foreach (get_declared_classes() as $class) { 
    $c = new $class; 
    if ($c instanceof Model) { 
     // it is a model 
     $c->getIncrementing(); 
    } 
} 

개체 인스턴스화에 try catch를 사용하여 오류를 catch 할 수 있습니다.

관련 문제