在Laravel的控制器中访问模型的正确方法是什么?


What is the correct way to access a model in an controller on Laravel

我是Laravel 4的新手,我正在努力理解它。

在Google和stackoverflow上搜索。也许我不是在寻找正确的语法,但我希望有人能帮助我,与它。

在CodeIgniter我理解它(可能)。这里我在控制器中使用:

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

但是在Laravel 4中呢?

我发现了以下内容:

我在de模型中创建了一个静态函数,所以我可以在任何地方访问它。例子:

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();
   }
}

我的问题是:有没有其他的方法和/或什么是正确的方法?

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

App::bind('ExampleModelInterface', 'Example');
class ExampleController extends BaseController {
    public function __construct(ExampleModelInterface $model)
    {
        $this->model = $model;
    }
}

您的意思是简单地访问模型的方法吗?

因为它们是静态的,所以使用:model::method()

你可能需要做一个composer dump- autolload,这样L4才能正确地自动加载它。