简体   繁体   English

Laravel 4动态模型调用

[英]Laravel 4 dynamic model call

I'm developing an API to acces some data on my database. 我正在开发一个API来访问我的数据库中的一些数据。 I'm creating a controller for each part of the API. 我正在为API的每个部分创建一个控制器。 For example, I will have a controller to attend API calls to get a film list (FilmsController) and other controller to attend API calls to get a director list (DirectorsController) 例如,我将有一个控制器参加API调用以获取电影列表(FilmsController)和其他控制器参加API调用以获取导演列表(DirectorsController)

Each controller will have a basic set of methods (getList, getInfo) so I made an ApiController to use as the base for the others. 每个控制器都有一组基本的方法(getList,getInfo),所以我创建了一个ApiController作为其他控件的基础。 In the ApiController I have the basic set of methods but I have to call the models in non very polite way. 在ApiController中,我有基本的方法集,但我必须以非常礼貌的方式调用模型。

I'm I missing something? 我错过了什么? Is there any other way to call the models dynamically? 有没有其他方法动态调用模型? I'm using the controllers wrong? 我使用控制器错了?

Here is the code, thanks. 这是代码,谢谢。

class ApiController extends BaseController {

    protected $model = '';

    public function getList() 
    {
        $items = call_user_func(array($this->model,'all'));
        return Response::json($items);
    }
    ...

} }

And the FilmsController 和FilmsController

class FilmsController extends ApiController {

    protected $model = 'Film';

}

Am I going with a bad design? 我的设计糟糕吗?

If you really want to bind model to controller, it would be better to use Laravel IoC container and its automatic resolution feature. 如果您真的想将模型绑定到控制器,最好使用Laravel IoC容器及其自动分辨率功能。

class ApiController extends BaseController {

    protected $model;

    public function getList() 
    {
        $items = $this->model->all();
        return Response::json($items);
    }
}

class FilmsController extends ApiController {

    public function __construct(Model $model)
    {
        $this->model = $model;
    }
}

Find more about this in documentation 文档中查找更多相关信息

why you call model using variable and use call_user_func function 为什么使用变量调用model并使用call_user_func函数

you can just create ApiController as abstract class and you override the basic set of methods (getList, getInfo) into FilmsController and DirectorsController then you can use Film Model 您可以将ApiController创建为抽象类,并将基本的方法集(getList,getInfo)覆盖到FilmsController和DirectorsController中,然后就可以使用Film Model

ApiController: ApiController:

class ApiController extends BaseController {


    public function getList() 
    {
    }

FilmsController: FilmsController:

class FilmsController extends ApiController {

                public function getList() 
                {
                   $items = Film::all();
                   return Response::json($items);


                }

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM