简体   繁体   English

在Laravel中,我应该将该代码存储在哪里?

[英]In Laravel, where should I store this code?

Using Laravel to develop a web app I'm facing some unclearity where to put some code. 使用Laravel开发Web应用程序时,我不清楚在哪里放置一些代码。

I have a User-like model that gets its data from another database. 我有一个类似用户的模型,该模型从另一个数据库获取数据。 I can only read in that database but that's fine. 我只能在该数据库中读取,但这很好。 Fields like name, city and so are very inconsistently stored in the database. 名称,城市等字段在数据库中的存储非常不一致。 For example sometimes a name is fully capitalized, other times it's not. 例如,有时候一个名字是全大写的,而有时候则不是。 So I've created a method formatAsName which currently resides in my UserController . 因此,我创建了一个formatAsName方法,该方法当前位于UserController

But the thing is, every time a user-like object is retreived from the database I'd like to use this method for some columns (like name and city). 但事实是,每次从数据库检索类似用户的对象时,我都想对某些列(例如名称和城市)使用此方法。 Should this code be stored in the controller, or does it belong to the model? 该代码应该存储在控制器中还是属于模型?

Side question: is there a way to tell Laravel to perform a callback when executing a query for this model? 附带问题:是否有一种方法可以告诉Laravel在执行此模型的查询时执行回调? Ortherwise I have to manually write some of the core Model-methods. 否则,我必须手动编写一些核心的Model方法。 This is no problem to do since there's limited interaction (only retrieval) but if it's supported that would be the best way. 这是没有问题的,因为交互作用有限(仅检索),但是如果支持,那将是最好的方法。

Thanks for your time. 谢谢你的时间。

您也可以在模型中定义方法,并且在laravel中有很多方法,您可以在此处找到更多帮助以获取代码指导:- 这里

I know you already got your answer, but I still want to give you a tip. 我知道您已经得到了答案,但是我仍然想给您一些提示。

A good approach for this case is to use the Repository Pattern. 对于这种情况,一种好的方法是使用存储库模式。 Doing that you can create Presenters and Transformers for your model and define how you want your models to be retrieved 这样,您可以为模型创建Presenter和Transformers并定义如何检索模型

    public function transform(User $model)
        {
            return [
                'name'         => strtolower($model->name),
                'city'         => strtolower($model->city),
                'created_at'    => Carbon::parse($model->created_at)->format('d-m-Y'),
                'updated_at'    => Carbon::parse($model->updated_at)->format('d-m-Y'),
            ];
        } 

Sorry but I don't have any source/material to send you about this pattern, but surely you can find it on google. 抱歉,我没有任何资料可发送给您有关此模式的信息,但是您可以在Google上找到它。 You can check my github if you want and take a look on this repo which have an example https://github.com/cbcaio/base-laravel 您可以检查我的github并查看此仓库,其中有一个示例https://github.com/cbcaio/base-laravel

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

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