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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16871593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:51:24  来源:igfitidea点击:

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

phplaravellaravel-4

提问by raymond.idema

I'm new on Laravel 4 and I am trying to understand it.

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

is searched on google and on stackoverflow. Maybe i am not searching for the right syntax but i hope someone can help me, with it.

在 google 和 stackoverflow 上搜索。也许我没有在寻找正确的语法,但我希望有人可以帮助我。

In CodeIgniter i understand it (probably). There I use in an Controller:

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

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

But how about in Laravel 4?

但是在 Laravel 4 中呢?

I figured out the following:

我想出了以下几点:

i make a static function in de model so i can access it everywhere. Example:

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

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

Or i could do it like this:

或者我可以这样做:

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

My question is: Is there an other way and/or what is the correct way?

我的问题是:还有其他方法和/或正确的方法吗?

回答by Ochi

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

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

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

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

回答by Johnny

Do you mean simply accessing the method of a model?

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

Since they are static you use: Modell::method()

由于它们是静态的,因此您使用:Modell::method()

You might have to do a composer dump-autoload though so L4 autoloads it correctly.

您可能需要执行 composer dump-autoload 以便 L4 正确自动加载它。