简体   繁体   中英

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.

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 .

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? Ortherwise I have to manually write some of the core Model-methods. 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

    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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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