2013-06-01 64 views
1

我是Laravel 4的新手,我試圖理解它。在Laravel的控制器中訪問模型的正確方法是什麼

在谷歌和搜索器上搜索。也許我不是在尋找正確的語法,但我希望有人可以幫助我。

在CodeIgniter我明白它(可能)。我在控制器中使用:

function __construct() 
{ $this->load->model('example_m'); } 

但是在Laravel 4中怎麼樣?

我想通了以下內容:

我使德模型的靜態函數,這樣我可以隨處訪問它。例如:

class Example extends Eloquent // this is the model 
{ 
    public static function TestExample(){ 
     // do some stuff here 
    } 
} 

我也可以做這樣的:

class ExampleController extends BaseController 
{ 
    public $test = null; 
    public function __construct() 
    { 
     $this->test = new Example(); 
    } 
    public function index() 
    { 
     $this->test->TestExample(); 
    } 
} 

我的問題是:有沒有其他的方式和/或什麼是正確的方法是什麼?

回答

5

http://four.laravel.com/docs/ioc

App::bind('ExampleModelInterface', 'Example'); 

class ExampleController extends BaseController { 
    public function __construct(ExampleModelInterface $model) 
    { 
     $this->model = $model; 
    } 
} 
1

你的意思簡單地訪問模型的方法是什麼?

由於它們是靜態的使用:產品型號::()方法

你可能要做一個作曲家轉儲自動加載,但這樣L4正確自動加載它。

相關問題